将MUI中的TextField与react钩子表单一起更新.onChange未被调用


const [userData, setUserData] = useState({
fullName: "",
email: "",
}); // Local component state
const onChange = (event) => {
console.log(event.target.value);
}; // Evente handler
<Grid container spacing={1}>
<Grid item xs={12} sm={12}>
<TextField
required
id="name"
name="fullName"
onChange={onChange}
label="Name"
InputLabelProps={{ shrink: true }}
fullWidth
value={userData.fullName}
margin="dense"
/>
<Typography variant="inherit" color="textSecondary">
{errors.fullName?.message}
</Typography>
</Grid>
<Grid item xs={12} sm={12}>
<TextField
required
id="email"
name="email"
label="Email"
onChange={onChange}
fullWidth
margin="dense"
value={userData.email}
{...register("email")}
error={errors.email ? true : false}
/>
<Typography variant="inherit" color="textSecondary">
{errors.email?.message}
</Typography>
</Grid>

由于某种原因,onChange没有被调用。我也使用Yup进行验证。我需要更新输入值并将其发送到API。但由于某些原因,事件处理程序未被称为

您正在用{...register("email")}的排列覆盖onChange道具,因为register调用将返回一个对象,其中一个属性名为onChange,RHF需要更新其内部表单状态。因此,在使用RHF时,您根本不需要自己的onChange处理程序,因为您可以直接通过RHF访问当前的<TextField />值。您只需要通过useFormdefaultValues传递默认值,或者直接将其传递给<Controller />,而不是直接通过value道具进行设置。

我还建议使用<Controller />,因为对于register,您将失去为<TextField />输入元素设置正确ref的功能,因为它是通过inputRef道具链接的,而不是使用RHFregister使用的ref。当你想在提交表格时验证失败时立即聚焦字段时,这就派上了用场。

您还可以使用<TextField />errorhelperText道具来显示您的错误,并通过<Controller />fieldState对象访问它以获得当前的验证错误(如果有(。

<Grid container spacing={1}>
<Grid item xs={12} sm={12}>
<Controller 
control={control}
name="fullName"
defaultValue={userData.fullName}
render={({ field: { ref, ...field }, fieldState: { error } }) => (
<TextField
required
id={field.name}
label="Name"
InputLabelProps={{ shrink: true }}
fullWidth
margin="dense"
error={!!error}
helperText={error?.message}
/>
)}
/>
</Grid>
<Grid item xs={12} sm={12}>
<Controller 
control={control}
name="email"
defaultValue={userData.email}
render={({ field: { ref, ...field }, fieldState: { error } }) => (
<TextField
required
id={field.name}
label="Name"
InputLabelProps={{ shrink: true }}
fullWidth
margin="dense"
error={!!error}
helperText={error?.message}
/>
)}
/>
</Grid>
</Grid>

最新更新