【发布时间】:2021-02-23 10:54:39
【问题描述】:
我正在尝试使用带有 Material UI 输入的 react-hook-forms 构建一个表单(在这种情况下,我是 TextField 的自定义变体)。尽管表单似乎工作得很好,但在呈现表单时会在控制台中触发警告消息。
警告:函数组件不能被赋予 refs。尝试去 访问此 ref 将失败。你的意思是使用 React.forwardRef() 吗?
我正在使用 react-hook-form 的控制器来包装我的 TextField(按照文档的建议)
非常欢迎任何建议或解决方案!
在 TextField 组件和出现此问题的表单下方:
组件文本字段
const TextField = props => {
const {
icon,
disabled,
errors,
helperText,
id,
label,
value,
name,
required,
...rest
} = props;
const classes = useFieldStyles();
return (
<MuiTextField
{...rest}
name={name}
label={label}
value={value || ''}
required={required}
disabled={disabled}
helperText={helperText}
error={errors}
variant="outlined"
margin="normal"
color="primary"
InputProps={{
startAdornment: icon,
classes: {
notchedOutline: classes.outline,
},
}}
InputLabelProps={{
className: classes.inputLabel,
}}
/>
)
};
TextField.propTypes = {
icon: PropTypes.node,
disabled: PropTypes.bool,
label: PropTypes.string,
id: PropTypes.string,
value: PropTypes.any,
required: PropTypes.bool,
helperText: PropTypes.string,
};
export default TextField;
组件登录表单
const LoginForm = () => {
const { handleSubmit, errors, control } = useForm();
const onSubmit = values => console.log(values);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Typography variant="h5" color="primary" gutterBottom>
Login
</Typography>
<Box py={3} height="100%" display="flex" flexDirection="column">
<Controller
as={TextField}
label="Username"
name="username"
control={control}
errors={errors}
required
/>
<Controller
as={TextField}
label="Password"
type="password"
name="password"
control={control}
errors={errors}
required
/>
<Link>
Forgot your password?
</Link>
</Box>
<Button variant="contained" color="primary" fullWidth type="submit">
Submit
</Button>
</form>
)
};
【问题讨论】:
标签: reactjs material-ui react-hook-form