我正在使用 Material UI 构建表单并使用 React Hook 表单进行验证。除了自动完成之外,它可以完美地使用 react hook form 的 Controller 组件。虽然它捕获自动完成数据,但错误处理不起作用。我假设这是因为当错误对象从 Controller => Autocomplete 传递下来时,它没有传递到嵌套的 TextField 组件。如果我改为对自动完成组件进行错误验证,它也不起作用。有人解决了这个问题吗?我的组件代码如下
<Controller
name="categories"
control={control}
defaultValue=''
render={(props) =>
<Autocomplete
className='formInputs'
options={categories}
renderInput={params =>
<TextField
name='autoCompleteTextField'
{...params}
// value={props.field.value}
label="What do you do?"
variant="outlined"
rules={{
required: {
value: true,
message: "Please tell us what you're an expert on. It helps us prioritize your referrals"
}
}}
error={Boolean(props.fieldState.error)}
onChange={(e, data) => props.field.onChange(data)}
{...props}
/>
}
/>
}
/>
最佳答案
您应该将渲染回调的 Prop 传播到 Autocomplete
组件,而不是 TextField
。看看官方example .此外,规则 Prop 应放在 Controller
中。组件。
<Controller
name="country"
control={control}
rules={{
required: "Please enter something"
}}
为了显示来自react-hook-form
的错误消息,您需要设置helperText
TextField
renderInput={(params) => (
<TextField
{...params}
label="Choose a country"
variant="outlined"
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
完整示例
<Controller
name="country"
control={control}
rules={{
required: "Please enter something"
}}
render={({ field, fieldState }) => {
return (
<Autocomplete
{...field}
options={countries}
getOptionLabel={(option) => option.label}
renderOption={(option) => (
<span>
{countryToFlag(option.code)}
{option.label}
</span>
)}
renderInput={(params) => (
<TextField
{...params}
label="Choose a country"
variant="outlined"
error={!!fieldState.error}
helperText={fieldState.error?.message}
/>
)}
onChange={(_, data) => field.onChange(data)}
/>
);
}}
/>
关于reactjs - 使用 Material UI 自动完成和 React Hook 表单进行错误验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69295842/