React Material-UI TextField深色主题下自动填充背景变白,如何匹配官方登录页样式
Material-UI 深色主题 TextField 自动填充白色背景问题解决方案
问题根因
- 出现异常白色背景的触发逻辑是Chrome、Edge等Webkit内核浏览器会对自动填充的表单元素自动应用
:-webkit-autofill伪类的内置默认样式,该样式优先级极高,会强制覆盖输入框自身设置的背景色。 - 不管是选中历史输入建议,还是浏览器自动填充已保存的站点账号密码,两种场景都会触发该伪类生效,进而显示默认的白色背景。
调整步骤
1. 补全输入框基础背景样式
现有样式仅定义了边框颜色,未显式声明输入框背景,需补充透明背景设置,避免场景切换时样式错位:
'& .MuiOutlinedInput-root': { // 深色主题下设置为透明背景,匹配官方模板效果 backgroundColor: 'transparent', // 原有边框样式规则无需改动 '& fieldset': { borderColor: 'white', }, '&:hover fieldset': { borderColor: 'white', }, '&.Mui-focused fieldset': { borderColor: 'yellow', } }
2. 新增自动填充伪类样式覆盖
注意:直接给自动填充伪类设置background-color无法覆盖浏览器默认样式,需要通过内阴影铺满输入框区域实现自定义背景,在withStyles的根样式下补充对应选择器:
'& .MuiOutlinedInput-root:-webkit-autofill, & .MuiOutlinedInput-root:-webkit-autofill:hover, & .MuiOutlinedInput-root:-webkit-autofill:focus': { // 用内阴影铺满输入框,替换默认的白色背景 WebkitBoxShadow: '0 0 0 1000px transparent inset', // 匹配自定义的文字颜色,避免自动填充默认的深色文字 WebkitTextFillColor: '#fff', // 匹配光标颜色 caretColor: '#f5f5f5', // 延迟自动填充默认背景的显示时间,避免白色闪烁 transition: 'background-color 9999s ease-out 0s' }
调整后的完整组件代码
const CssTextField = withStyles({ root: { '& .MuiInput-underline:after': { borderBottomColor: 'yellow', }, '& .MuiOutlinedInput-root': { backgroundColor: 'transparent', '& fieldset': { borderColor: 'white', }, '&:hover fieldset': { borderColor: 'white', }, '&.Mui-focused fieldset': { borderColor: 'yellow', }, // 覆盖浏览器自动填充的默认白色背景 '&:-webkit-autofill, &:-webkit-autofill:hover, &:-webkit-autofill:focus': { WebkitBoxShadow: '0 0 0 1000px transparent inset', WebkitTextFillColor: '#fff', caretColor: '#fff', transition: 'background-color 9999s ease-out 0s' } }, }, })(TextField); export default function SignIn(props) { return ( <form className={classes.form} noValidate> <CssTextField variant="outlined" margin="normal" required fullWidth id="email" label="userName" name="text" type="text" autoComplete="text" autoFocus InputLabelProps={{ style: { color: '#fff' }, }} InputProps={{ style: { color: "red" } }} /> </form> ) }
补充注意事项
WebkitBoxShadow的内阴影值是兼容Webkit浏览器自动填充的通用写法,直接设置background-color会被浏览器内置样式拦截,无法生效。- 如果你使用MUI v5版本,可以把这套自动填充覆盖规则配置到全局主题的
MuiOutlinedInput组件默认样式中,无需逐个输入框重复编写。 - 补充上述规则后,无论是选中历史输入建议还是触发浏览器自动填充,TextField的背景都会和官方登录页深色主题效果保持一致,不会出现突兀的白色块。
内容的提问来源于stack exchange,提问作者rider
相关产品推荐
相关产品推荐

