#javascript #reactjs
#javascript #reactjs
Вопрос:
У меня есть форма, в которой я использую react-DatePicker, чтобы позволить пользователю выбрать свой день рождения. Компонент находится внутри формы. Однако, когда моя форма отправлена, я не смог зарегистрировать выбранную дату рождения на консоли.
Вот часть кода формы с компонентом DatePicker:
const Register = () => {
const [modalIsOpen, setModalIsOpen] = useState (true)
const { register, handleSubmit, errors } = useForm ();
const [date, setDate] = useState(new Date());
const handleCalendarClose = () => console.log(date);
const handleCalendarOpen = () => console.log("Calendar opened");
const onSubmit = (data) => console.log(data);
const [passwordShown, setPasswordShown] = useState(false);
const togglePasswordVisiblity = () => {
setPasswordShown(passwordShown ? false : true);
};
return(
<Modal isOpen={modalIsOpen} onRequestClose={() => setModalIsOpen(false)} className='createBorder'>
<form>
<p className='fieldsOne'>First name:</p>
<input name='firstName' ref={register({required: true})} className='inputs' autoComplete='off'></input>
<p className='minifields'>This information will display on your profile</p>
{errors.firstName amp;amp; <span className='registerRequired'>This field is required</span>}
<p className='fields'>Last name:</p>
<input name='lastName' ref={register({required: true})} className='inputs' autoComplete='off'></input>
<p className='minifields'>This information will display on your profile</p>
{errors.lastName amp;amp; <span className='registerRequired'>This field is required</span>}
<p className='fields'>Birthdate:</p>
{/* datepicker is not logged to the console because it is not an input field it is a component, how can we wrap the component */}
<DatePicker
ref={register({required: true})}
dateFormat="MM/dd/yyyy"
selected={date}
name='Birthday'
onChange={date => setDate(date)}
onCalendarClose={handleCalendarClose}
onCalendarOpen={handleCalendarOpen}
/>
<p className='minifields'>We'll use this information when considering what films you are qualified to test</p>
{errors.Birthdate amp;amp; <span className='registerRequired'>This field is required</span>}
</form>
<div className='alignalign'>
<a href='/GetStarted/completeProfile' onClick={handleSubmit(onSubmit)} type='submit' className='signupButton'>Sign Up</a>
</div>
</Modal>
Спасибо в расширенном
Ответ №1:
Какие бы данные не были включены в данные from, вы просто добавляете их в объект data во время обработки.
const onSubmit = (data) => {data['birthdate']= date; console.log(data);}