我有一个react组件:
const CustomDatePicker = ({ errors, id, name, control, rules, getValues, minDate, maxDate, placeholder, required, defaultValue, ...rest }) => {
console.log("required 1", name, required);
const inputRef = React.useRef();
const validateField = () => {
console.log("required 2", required, name)
if (required && !getValues(name)) {
return false
}
else if (getValues(name)) {
let dateObj = typeof (getValues(name)) == 'string' ? new Date(getValues(name)) : getValues(name)
return !isNaN(dateObj);
}
else return true;
}
return (
<div className="form-group custom-input-container">
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Controller
name={name}
margin="normal"
fullWidth
variant="outlined"
onFocus={() => {
if (inputRef.current) {
inputRef.current.focus()
}
}}
defaultValue={defaultValue}
as={<KeyboardDatePicker
inputRef={inputRef}
className="custom-date-col"
fullWidth
autoOk
clearable
variant="inline"
inputVariant="outlined"
placeholder={placeholder}
minDate={minDate}
format="dd-MM-yyyy"
maxDate={maxDate}
/>}
rules={{
validate: validateField
}}
control={control}
errors={errors}
{...rest}
/>
</MuiPickersUtilsProvider>
</div>
);
};
export default CustomDatePicker;
和上级组件按以下方式使用上述内容:
export default function Dummy(props) {
const [req,setReq]=useState(false);
return (
<div className="FamilyDetails__emergency-form-row FamilyDetails__three-col-grid">
<CustomDatePicker
name={`marriageDate`}
errors={props.errors}
control={props.control}
maxDate={new Date()}
minDate={getMinDate()}
placeholder={"dateOfMarriageLbl"}
required={req}
defaultValue={new Date()}
/>
</div>
);
}
我在表格中使用上述组件。最初,“必需”道具将为假,然后将其更改为真。当我提交表单时,将调用validateField
方法,并且控制台中的required
属性值将打印为false,而原始值为true。然后,在函数外部打印的控制台将“ require”属性值打印为true。 validateField
函数中“必需” prop的值采用初始值,该值是最初用于渲染组件的。请帮助我。