如何在Material UI的TextField中将占位符内的星号设为红色加粗?
解决方案:给Material UI TextField占位符中的星号单独设置红色加粗样式
原生HTML input的placeholder属性不支持为部分文本设置单独样式,因此需要通过模拟占位符的方式实现需求。以下是两种可行的实现方式:
方式一:自定义输入组件(推荐)
通过TextField的inputComponent属性自定义输入框结构,用带样式的元素模拟占位符,单独对星号设置样式:
import { TextField, Box, InputProps } from '@mui/material'; // 自定义输入组件 const CustomInput = (props: InputProps) => { const { value, onChange, ...rest } = props; return ( <div style={{ position: 'relative', display: 'inline-block', width: '100%' }}> <input {...rest} value={value} onChange={onChange} style={{ width: '100%', padding: '10.5px 14px' }} // 匹配Outlined输入框的内边距 /> {/* 模拟占位符,仅当输入为空时显示 */} {!value && ( <div style={{ position: 'absolute', left: '14px', top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', // 避免干扰输入交互 color: 'rgba(0, 0, 0, 0.6)', // 匹配原生占位符默认颜色 fontSize: '1rem', }} > ddd <span style={{ color: 'red', fontWeight: 'bold' }}>*</span> </div> )} </div> ); }; export default function BasicTextFields() { return ( <Box component="form" sx={{ "& > :not(style)": { m: 1, width: "25ch" } }} noValidate autoComplete="off" > <TextField id="outlined-basic" label="" variant="outlined" inputComponent={CustomInput} /> </Box> ); }
方式二:利用InputAdornment结合状态控制
通过InputProps的装饰元素,配合输入值的状态显示带样式的星号,调整位置以匹配占位符布局:
import { TextField, Box, InputAdornment, Typography, useState } from '@mui/material'; export default function BasicTextFields() { const [value, setValue] = useState(''); return ( <Box component="form" sx={{ "& > :not(style)": { m: 1, width: "25ch" } }} noValidate autoComplete="off" > <TextField id="outlined-basic" label="" placeholder="ddd" variant="outlined" value={value} onChange={(e) => setValue(e.target.value)} InputProps={{ startAdornment: !value && ( <InputAdornment position="start" sx={{ marginLeft: '38px', pointerEvents: 'none' }}> <Typography sx={{ color: 'red', fontWeight: 'bold' }}>*</Typography> </InputAdornment> ), }} /> </Box> ); }
说明
- 方式一的模拟占位符完全复刻原生占位符的视觉和交互表现,适配性更强;
- 方式二实现更简洁,但需要根据输入框的样式(如内边距、字体大小)调整装饰元素的位置参数。
内容的提问来源于stack exchange,提问作者user5711656
相关产品推荐
相关产品推荐

