我有一个使用Yup进行验证的Formik表单。我的一个字段是日期选择器,但我无法将其集成到Yup验证中。
下面的代码可以渲染组件,但是当我尝试将<DatePicker/>
Package 在<Field name="date></Field>
标记中时,什么也渲染不了。
const [fieldDate,setFieldDate] = useState ("");
const dateSchema = Yup.object().shape({
date: Yup.date().required('Date is required'),
});
const initialValues = {date:''};
return (
<div>
<FormContainer>
<Formik
initialValues={initialValues}
//validationSchema={loginValidationSchema}
validationSchema={dateSchema}
onSubmit={()=>{console.log ("ok")}}
>
{({ isSubmitting, values, setFieldValue, handleChange, handleBlur, errors, touched }) => (
<Form className="form">
<LocalizationProvider dateAdapter={DateFnsUtils}>
<DatePicker
label="Date"
value={fieldDate}
onChange={(newValue:any) => {
setFieldDate(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
<div className="buttonWrapper">
<SubmitButton type="submit" className="SubmitButton">Submit</SubmitButton>
</div>
</Form>
)}
</Formik>
</FormContainer>
</div>
这里是我的导入...我将它们包括在内是因为我发现MUI中有多个同名的库,它们具有不同的父目录和不同的要求,这在某种程度上增加了我通过在线解决方案解决此问题时的困惑:
import React, { useState} from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import {FormContainer,FieldContainer, SubmitButton } from "../GlobalStyle";
import { TextField } from "@mui/material";
import * as Yup from "yup";
import "react-datepicker/dist/react-datepicker.css";
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import DateFnsUtils from "@date-io/date-fns";
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
谢谢你!
1条答案
按热度按时间z9ju0rcb1#