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 />
值。您只需要通过useForm
defaultValues
传递默认值,或者直接将其传递给<Controller />
,而不是直接通过value
道具进行设置。
我还建议使用<Controller />
,因为对于register
,您将失去为<TextField />
输入元素设置正确ref
的功能,因为它是通过inputRef
道具链接的,而不是使用RHFregister
使用的ref
。当你想在提交表格时验证失败时立即聚焦字段时,这就派上了用场。
您还可以使用<TextField />
的error
和helperText
道具来显示您的错误,并通过<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>