reactjs 当有开始装饰时,如何将标签放置在Material UI TextField组件中的输入文本上方?

yc0p9oo0  于 2023-10-17  发布在  React
关注(0)|答案(2)|浏览(107)

正如标题所说,我一直在努力做到这一点,但对于我的生活,我不知道哪个材质用户界面css类操纵来完成这一点。我试过使用InputLabelProps(确切地说是收缩类),但它就是不起作用。我创建了一个可重用的TextField组件:

const useStyles = makeStyles({
    textFieldInput: {
        fontFamily: globalFonts.montserrat,
        fontSize: 13,
        fontWeight: "bold",
    },
    textFieldRoot: {
        borderRadius: 8,
        backgroundColor: "white",
        border: "1px solid #F5F5F5",
    }
});

export default function TextInput({error, label, onChange, value, InputLabelProps, InputProps, inputProps, icon, disabled, type, helperText}: Props) {
    const classes = useStyles();

    return (
        <TextField
            type={type}
            fullWidth
            label={label}
            value={value}
            variant='filled'
            onChange={(e) => {onChange(e)}}
            inputProps={inputProps}
            InputProps={
                InputProps ? InputProps :
                {
                    classes: {input: classes.textFieldInput, root: classes.textFieldRoot},
                    startAdornment: icon ? <InputAdornment position='start'>{icon}</InputAdornment> : undefined,
                    disableUnderline: true,                    
                }
            }
            InputLabelProps={InputLabelProps}
            error={error ? error(value) : false}
            helperText={helperText}
            disabled={disabled}
        />
    )
}

有没有人知道如何将标签放置在输入的文本上方,或者你们以前遇到过这个问题?
沙盒链接:https://codesandbox.io/s/quizzical-cdn-c6p3xc

neekobn8

neekobn81#

您可以使用TextField组件的InputLabelProps。具体来说,您应该将shrink属性设置为true,以便在输入字段获得焦点或具有内容时使标签收缩。

export default function TextInput({error, label, onChange, value, InputProps, inputProps, icon, disabled, type, helperText}: Props) {
    const classes = useStyles();

    return (
        <TextField
            type={type}
            fullWidth
            label={label}
            value={value}
            variant='filled'
            onChange={(e) => {onChange(e)}}
            inputProps={inputProps}
            InputProps={
                InputProps ? InputProps :
                {
                    classes: {input: classes.textFieldInput, root: classes.textFieldRoot},
                    startAdornment: icon ? <InputAdornment position='start'>{icon}</InputAdornment> : undefined,
                    disableUnderline: true,                    
                }
            }
            InputLabelProps={{
                shrink: true, // This will make the label shrink when focused or has content
            }}
            error={error ? error(value) : false}
            helperText={helperText}
            disabled={disabled}
        />
    )
}
v9tzhpje

v9tzhpje2#

向标签添加marginLeft就可以了

label: {
    "&.MuiInputLabel-filled.MuiInputLabel-shrink": {
      color: "#000000",
      fontWeight: 400,
      fontFamily: "Montserrat-Medium",
      marginLeft: "35px"
    }
  },

相关问题