この記事はこんな人におすすめ
- MUI における TextField の入力欄に固定の文字列を表示する方法を知りたい
公式サイトの情報はコチラ。
環境
React: 17.0.2
MUI: 5.5.2
入力欄に固定の文字列を表示する
TextField には、以下の書式を使用して、固定の文字列を表示することができます。
<TextField label="Standard" variant="standard" InputProps={{ startAdornment: ( <InputAdornment position="start"> // 固定で表示する文字列をここに記載 </InputAdornment> ), }}/>
以下は、入力欄に単位「Kg」の固定文字列を表示する例です。
import InputAdornment from '@mui/material/InputAdornment'; import TextField from '@mui/material/TextField'; import { Stack } from '@mui/material'; import { PhoneIphone } from '@mui/icons-material'; export default function TextFieldSample6() { return ( <> <Stack spacing={2} direction="row"> {/* TextField に固定の文字列をを表示する方法 */} <TextField id="outlined-basic" label="Outlined" variant="outlined" InputProps={{ startAdornment: ( <InputAdornment position="start"> Kg </InputAdornment> ), }}/> <TextField id="filled-basic" label="Filled" variant="filled" InputProps={{ startAdornment: ( <InputAdornment position="start"> Kg </InputAdornment> ), }}/> <TextField id="standard-basic" label="Standard" variant="standard" InputProps={{ startAdornment: ( <InputAdornment position="start"> Kg </InputAdornment> ), }}/> </Stack> </> ); }
入力欄の末尾に固定の文字列を表示する
先ほどの例では、入力欄の先頭に固定の文字列を表示しました。
入力欄の末尾に固定の文字列を表示したい場合は、以下の書式のように endAdornment: とposition=”end” を使用します。
<TextField label="Standard" variant="standard" InputProps={{ endAdornment: ( <InputAdornment position="end"> // ここに入力欄の末尾に表示する固定の文字列を記載 </InputAdornment> ), }}/>
以下は先ほどの例を使用して、アイコンを末尾に表示するようにした例です。
import InputAdornment from '@mui/material/InputAdornment'; import TextField from '@mui/material/TextField'; import { Stack } from '@mui/material'; import { PhoneIphone } from '@mui/icons-material'; export default function TextFieldSample6() { return ( <> <Stack spacing={2} direction="row"> {/* TextField の末尾に固定の文字列を表示する方法 */} <TextField id="outlined-basic" label="Outlined" variant="outlined" InputProps={{ endAdornment: ( <InputAdornment position="end"> Kg </InputAdornment> ), }}/> <TextField id="filled-basic" label="Filled" variant="filled" InputProps={{ endAdornment: ( <InputAdornment position="end"> Kg </InputAdornment> ), }}/> <TextField id="standard-basic" label="Standard" variant="standard" InputProps={{ endAdornment: ( <InputAdornment position="end"> Kg </InputAdornment> ), }}/> </Stack> </> ); }
MUI Tips 一覧
その他の MUI Tips 一覧はコチラを参照してください。
Please follow and like us:
コメント