Material-UI输入框边框颜色无法修改?需设默认/悬浮/聚焦为白色
解决Material-UI OutlinedInput边框颜色不生效问题
问题原因
Material-UI的OutlinedInput组件边框并非直接通过borderColor控制,而是依赖CSS伪元素实现不同状态样式:
- 默认状态边框:
&:before - 悬浮未聚焦状态边框:
&:hover:not(.Mui-focused):before - 聚焦状态边框:
&:after
你的代码直接设置borderColor无法命中这些伪元素,同时类名挂载位置错误导致样式层级不匹配。
解决方案
方式1:修正makeStyles写法并调整类名挂载位置
先更新useStyles的样式规则,针对伪元素设置边框颜色:
const useStyles = makeStyles((theme) => ({ textField: { '& .MuiOutlinedInput-root': { // 默认状态边框 '&:before': { borderColor: 'white', }, // 悬浮未聚焦状态边框 '&:hover:not(.Mui-focused):before': { borderColor: 'white', }, // 聚焦状态边框 '&:after': { borderColor: 'white', }, }, '& .MuiOutlinedInput-input': { color: 'white', }, '& .MuiInputAdornment-root': { color: 'white', }, // 聚焦时标签保持白色 '& .MuiInputLabel-root.Mui-focused': { color: 'white', }, }, }));
然后将classes.textField直接挂载到TextField组件本身,而非InputProps.classes.root:
<TextField type="number" name={name} value={value} onChange={handleChange} className={classes.textField} // 调整类名挂载位置 InputLabelProps={{ shrink: true, style: { color: 'white' }, }} InputProps={{ inputProps: { step: 1, min: 0, }, endAdornment: ( <InputAdornment position="end"> {isForm && ( <> <IconButton aria-label="increase" size="small" onClick={() => handleChange({ target: { name, value: parseInt(value || '0') + 1 } })} style={{ color: 'white' }} > <ArrowUpwardIcon /> </IconButton> <IconButton aria-label="decrease" size="small" onClick={() => handleChange({ target: { name, value: Math.max(parseInt(value || '0') - 1, 0) } })} style={{ color: 'white' }} > <ArrowDownwardIcon /> </IconButton> </> )} </InputAdornment> ), }} />
方式2:直接使用sx属性(Material-UI v5推荐)
如果不需要复用样式,可直接通过sx属性内联设置所有样式,更简洁:
<TextField type="number" name={name} value={value} onChange={handleChange} InputLabelProps={{ shrink: true, style: { color: 'white' }, }} InputProps={{ inputProps: { step: 1, min: 0, }, endAdornment: ( <InputAdornment position="end"> {isForm && ( <> <IconButton aria-label="increase" size="small" onClick={() => handleChange({ target: { name, value: parseInt(value || '0') + 1 } })} style={{ color: 'white' }} > <ArrowUpwardIcon /> </IconButton> <IconButton aria-label="decrease" size="small" onClick={() => handleChange({ target: { name, value: Math.max(parseInt(value || '0') - 1, 0) } })} style={{ color: 'white' }} > <ArrowDownwardIcon /> </IconButton> </> )} </InputAdornment> ), }} sx={{ '& .MuiOutlinedInput-root': { '&:before': { borderColor: 'white' }, '&:hover:not(.Mui-focused):before': { borderColor: 'white' }, '&:after': { borderColor: 'white' }, '& .MuiOutlinedInput-input': { color: 'white' }, }, '& .MuiInputAdornment-root': { color: 'white' }, '& .MuiInputLabel-root.Mui-focused': { color: 'white' }, }} />
内容的提问来源于stack exchange,提问作者the56hjkl
相关产品推荐
相关产品推荐

