如何解决 Material UI 中
InputLabel
和 OutlinedInput
的重叠问题?
<FormControl>
<InputLabel htmlFor="my-input">Email address</InputLabel>
<OutlinedInput id="my-input" aria-describedby="my-helper-text" />
<FormHelperText id="my-helper-text">
We'll never share your email.
</FormHelperText>
</FormControl>
<hr />
<br />
<FormControl>
<InputLabel shrink={true} htmlFor="my-input">
Email address
</InputLabel>
<OutlinedInput id="my-input" aria-describedby="my-helper-text" />
<FormHelperText id="my-helper-text">
We'll never share your email.
</FormHelperText>
</FormControl>
结果:
我尝试了
shrink={true}
,但不起作用。
您必须在 OutlinedInput 标签中添加“label”属性。
<OutlinedInput id="my-input" aria-describedby="my-helper-text" label="Email address"/>
要点: 方向:“ltr”确保标签文本对于从左到右的语言正确对齐。 &.MuiFormLabel-root:not(.MuiFormLabel-filled):not(.Mui-focused) 等规则可让您定位不同状态下的标签。 确保应用 ThemeProvider 来包装您的应用程序或特定组件以应用这些样式。
const const theme = createTheme({
components: {
...
MuiInputLabel:{
defaultProps:{},
styleOverrides:{
root:{
direction:"ltr",
width:"100%",
textAlign:"end",
fontSize:20,
"&.MuiFormLabel-root:not(.MuiFormLabel-filled):not(.Muifocused)":{color:'pink'},
"&.Mui-focused":{left:30,top:-10},
"&.MuiFormLabel-filled:not(.Mui-focused)":{left:30, top:-6}
},
},
},
},
) 在组件示例中
const OutLineInputWrap = ({
inputType,
label,
textColor,
textColorStateFilled,
textColorStateFocused,
value
,onChangeHndler
}:OutLineInputWrapType)=>{
return (
<FormControl sx={{ m: 1, }} variant="outlined">
<InputLabel
variant='outlined'
sx={{
"&.MuiFormLabel-root:not(.MuiFormLabel-filled):not(.Mui-focused)":{color:textColor},//init
"&.Mui-focused ":{color:textColorStateFocused},
"&.MuiFormLabel-filled:not(.Mui-focused)":{color:textColorStateFilled},
}}
htmlFor={label}>
{label}
</InputLabel>
<OutlinedInput
id={label}
label={label}
type={inputType}
value={value}
onChange={onChangeHndler}
/>
</FormControl>
)
}
export default OutLineInputWrap
type HTMLInputTypes =
| "button"
| "checkbox"
| "color"
| "date"
| "datetime-local"
| "email"
| "file"
| "hidden"
| "image"
| "month"
// | "number" not valid TS see https://stackoverflow.com/questions/61070803/how-to-handle-number-input-in-typescript
| "password"
| "radio"
| "range"
| "reset"
| "search"
| "submit"
| "tel"
| "text"
| "time"
| "url"
| "week";
interface OutLineInputWrapType {
inputType?: HTMLInputTypes
label:string
textColor?:CSSProperties['color']
textColorStateFocused?:CSSProperties['color']
textColorStateFilled?:CSSProperties['color']
value:string
onChangeHndler:ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>
}