我正在尝试将弹性 ui datepicker 与反应挂钩表单和 Yup 模式验证集成。我知道默认情况下,Yup 日期模式正在寻找一个常规的 js 日期或一个可以被解析的字符串,而弹性 ui 日期选择器接受并输出其日期的时刻。因此,我尝试在日期模式中添加一个转换器,以将值解析为片刻。当我尝试这个时,它永远不会记录我为日期选择了任何东西,并且变压器永远不会运行。这是一个例子:
import React, { useState } from "react";
import styled from "styled-components";
import {
EuiButton,
EuiForm,
EuiFormRow,
EuiFieldText,
EuiPage,
EuiPageBody,
EuiPageContent,
EuiPageHeader,
EuiTitle,
EuiPageHeaderSection,
EuiDatePicker,
} from "@elastic/eui";
import { useForm } from "react-hook-form";
import { useDispatch } from "react-redux";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import moment from "moment";
import { addUser } from "./logic";
const Container = styled.div`
text-align: initial;
`;
const momentSchema = yup.date().clone().transform(function (value, originalValue) {
if (this.isType(value)) {
return value;
}
value = moment(originalValue);
return value.isValid() ? value.toDate() : new Date("");
});
export const FormsPage = () => {
const schema = yup.object().shape({
firstName: yup.string().required(),
lastName: yup.string().required(),
email: yup.string().email().required(),
dob: momentSchema.required(),
});
const [dob, setDob] = useState();
const { errors, handleSubmit, register } = useForm({
resolver: yupResolver(schema),
});
const dispatch = useDispatch();
const onDobChange = (date) => {
setDob(date);
};
const onSubmit = (data) => {
dispatch(addUser(data));
};
return (
<Container>
<EuiPage>
<EuiPageBody>
<EuiPageHeader>
<EuiPageHeaderSection>
<EuiTitle size="1">
<h1>Forms</h1>
</EuiTitle>
</EuiPageHeaderSection>
</EuiPageHeader>
<EuiPageContent>
<EuiForm
component="form"
onSubmit={handleSubmit(onSubmit)}
noValidate
>
<EuiFormRow
label="First Name"
isInvalid={!!errors.firstName}
error={errors.firstName?.message}
>
<EuiFieldText
name="firstName"
inputRef={register}
isInvalid={!!errors.firstName}
/>
</EuiFormRow>
<EuiFormRow
label="Last Name"
isInvalid={!!errors.lastName}
error={errors.lastName?.message}
>
<EuiFieldText
name="lastName"
inputRef={register}
isInvalid={!!errors.lastName}
/>
</EuiFormRow>
<EuiFormRow
label="Email"
isInvalid={!!errors.email}
error={errors.email?.message}
>
<EuiFieldText
name="email"
inputRef={register}
isInvalid={!!errors.email}
/>
</EuiFormRow>
<EuiFormRow
label="Date of Birth"
isInvalid={!!errors.dob}
error={errors.dob?.message}
>
<EuiDatePicker
name="dob"
inputRef={register}
isInvalid={!!errors.dob}
selected={dob}
onChange={onDobChange}
/>
</EuiFormRow>
<EuiFormRow>
<EuiButton type="submit" fill>
Submit
</EuiButton>
</EuiFormRow>
</EuiForm>
</EuiPageContent>
</EuiPageBody>
</EuiPage>
</Container>
);
};
这就是发生的事情: 日期是必需的