我正在使用 React-Hook-Form 创建一个表单。我已设置useForm({mode: 'onBlur'})
立即触发验证并在用户 onBlur 元素后立即显示错误消息。对于输入文本字段,它工作正常。但是,它不适用于我的<Controller />
元素,它包装了一个自定义的<Select />
.
以下是我的代码:
import React from 'react';
import { useForm, Controller, ErrorMessage } from 'react-hook-form';
import Select from '../../components/UI/Select';
const departmentList = [
{ name: 'PLEASE SELECT', value: '' },
{ name: 'Finance', value: 'FIN' },
{ name: 'IT', value: 'IT' },
{ name: 'Business', value: 'BIZ' }
];
const Form = props => {
const { register, handleSubmit, control, errors } = useForm({ mode: "onBlur" });
const onSubmit = (data) => {
console.log(data);
}
return (
<form onSubmit={handleSubmit(onSubmit)} style={{backgroundColor: 'white'}}>
<div>
<label>First Name:</label>
<input type="text" name='firstName' ref={register({ required: 'First name cannot be null.' })} />
<ErrorMessage errors={errors} name='firstName' />
</div>
<div>
<label>Last Name:</label>
<input type='text' name='lastName' ref={register({ required: 'Last name cannot be null.' })} />
<ErrorMessage errors={errors} name='lastName' />
</div>
<div>
<label>Department:</label>
<Controller
as={<Select options={departmentList} />}
control={control}
valueName="selected"
rules={{ required: 'Department cannot be null.' }}
name="department"
/>
<ErrorMessage errors={errors} name='department' />
</div>
<input type="submit" value="Submit" />
</form>
);
}
export default Form;
以下是<Select />
元素:
import React from 'react';
const Select = props => {
let optionList = null;
if(props.options) {
optionList = props.options.map((o, i) => <option key={i} value={o.value}>{o.name}</option>)
}
return (
<select
className="form-control"
value={props.value}
style={props.style}
selected={props.selected}
onChange={props.onChange}
>
{ optionList }
</select>
);
};
export default Select;
点击选择后,选择空值,然后模糊,它不会显示错误消息onBlur。
有什么方法可以进行触发器验证并在 Blur 上显示错误消息?我错过了什么吗?