React TS中为MUI Autocomplete组件应用CSS类的方法求助
在React TS中为MUI Autocomplete组件应用自定义CSS类的解决方案
方法一:直接给TextField添加自定义类并覆盖MUI样式
Autocomplete的输入区域由renderInput返回的TextField渲染,直接给TextField添加自定义类,再通过CSS层级覆盖MUI默认样式:
修改Autocomplete的renderInput部分
renderInput={(params) => ( <TextField placeholder={t('firstname')} {...params} error={Boolean(errors?.firstName)} helperText={errors?.firstName?.message} {...register("firstName", { required: true })} // 添加自定义类及错误状态类 className={`form-control custom-form-control ${errors?.firstName ? 'is-invalid' : ''}`} /> )}
调整CSS优先级以覆盖MUI样式
/* 覆盖MUI输入框的基础样式 */ .form-control .MuiOutlinedInput-input { display: block; width: 100%; padding: 0.375rem 0.75rem; font-size: 1rem; font-weight: 400; line-height: 1.5; color: #212529; background-color: #fff; } .form-control .MuiOutlinedInput-root { border-radius: 0.25rem; border: 1px solid #ced4da; } /* 聚焦状态样式 */ .form-control:focus-within .MuiOutlinedInput-notchedOutline { border-color: #e9ca85 !important; box-shadow: 0 0 0 0.25rem rgba(211, 149, 11, 0.25) !important; } /* 错误状态样式 */ .form-control.is-invalid .MuiOutlinedInput-notchedOutline { border-color: #dc3545; box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25); }
方法二:修正styled-components定制逻辑
之前的自定义Styled TextField未生效,是因为选择器未针对文本输入框核心元素,调整如下:
import { styled } from '@mui/material/styles'; import TextField from '@mui/material/TextField'; const CustomTextField = styled(TextField)(({ theme }) => ({ '& .MuiOutlinedInput-root': { height: '38px', width: '100%', borderRadius: '0.25rem', border: '1px solid #ced4da', padding: theme.spacing(0.5), // 定制输入框内的文本样式 '& .MuiOutlinedInput-input': { padding: '0.375rem 0.75rem', fontSize: '1rem', lineHeight: '1.5', }, // hover状态 '&:hover .MuiOutlinedInput-notchedOutline': { borderColor: '#ced4da', }, // 聚焦状态 '&.Mui-focused .MuiOutlinedInput-notchedOutline': { borderColor: '#e9ca85', borderWidth: 2, boxShadow: '0 0 0 0.25rem rgba(211, 149, 11, 0.25)', outline: 0, }, }, // 错误状态 '&.Mui-error .MuiOutlinedInput-notchedOutline': { borderColor: '#dc3545', boxShadow: '0 0 0 0.25rem rgba(220, 53, 69, 0.25)', }, })); // 在Autocomplete中使用定制后的TextField renderInput={(params) => ( <CustomTextField placeholder={t('firstname')} {...params} error={Boolean(errors?.firstName)} helperText={errors?.firstName?.message} {...register("firstName", { required: true })} /> )}
方法三:使用standard变体减少MUI默认样式干扰
将TextField的variant设为standard,MUI会提供极简的基础样式,你的自定义类更容易生效:
renderInput={(params) => ( <TextField placeholder={t('firstname')} {...params} variant="standard" error={Boolean(errors?.firstName)} helperText={errors?.firstName?.message} {...register("firstName", { required: true })} className={`form-control custom-form-control ${errors?.firstName ? 'is-invalid' : ''}`} /> )}
此时你原本定义的.form-control和.form-control:focus样式可以直接生效,无需大量修改。
内容的提问来源于stack exchange,提问作者Maarten Baeten
相关产品推荐
相关产品推荐

