我正在尝试将 react-hook-form 与我的自定义日期选择器一起使用,但我只看到这个示例(Is it possible to use react-datepicker with react hooks forms?),它使用的是默认的 react-date-picker。
但是,它仅适用于原始的 react-date-picker。我用我的自定义日期选择器尝试了同样的方法,但它不起作用......
这是我自定义的日期选择器:
import React, { useState } from 'react';
import ReactDatePicker from 'react-datepicker';
import tw from "date-fns/locale/zh-TW";
import "react-datepicker/dist/react-datepicker.css";
const DatePicker = props => {
const [date, setDate] = useState('');
return (
<ReactDatePicker
className="form-control"
selected={date}
onChange={date => setDate(date)}
locale={tw}
dateFormat="yyyy/MM/dd"
dateFormatCalendar="yyyy年 MM月"
isClearable
/>
)
};
export default DatePicker;
这是我如何将 react-hook-form 与自定义的日期选择器一起使用:
import React from 'react';
import { useForm, Controller } from 'react-hook-form';
import DatePicker from '../../components/UI/Form/DatePicker';
const Form = props => {
const { register, handleSubmit, control} = useForm();
const onSubmit = (data) => {
console.log(data);
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>First Name:</label>
<input type="text" name='firstName' ref={register} />
<label>Last Name:</label>
<input type='text' name='lastName' ref={register} />
<label>birthday:</label>
<Controller as={DatePicker} control={control} valueName="selected" name="birthday" />
<input type="submit" value="Submit" />
</form>
);
}
export default Form;
提交表单后,“生日”值未定义。我还需要在我的自定义日期选择器中添加任何道具吗?
{生日:未定义,名字:“迈克”,姓氏:“史密斯”}