首先,我制作了一个用formik验证的表格。之后,我的团队决定使用 React-Bootstrap 进行样式设计。这个库有一个
<Form>
对象,与 Formik 相同。但它没有正确验证。它要么始终将输入字段视为无效,从而将其边框设为红色,要么始终将输入字段视为正确。
我怀疑这是一个组合库的问题,这些库既适用于表单,又具有同名的组件。我设法让它与原始引导库一起工作。但我还是想知道为什么会发生这种情况以及是否有解决方案。
import React, {useState} from 'react';
import '../FormStyles.css';
import * as yup from "yup";
import { Formik, Form, ErrorMessage, Field } from 'formik';
const TestimonialForm = ({ testimonial = null }) => {
const initialValues = {
name: testimonial?.name || "",
description: testimonial?.description || "",
image: testimonial?.image || ""
};
const schema = yup.object().shape({
name: yup.string().min(4, "Name must be at least 4 characters long.").required("You have to provide a name."),
description: yup.string().required("You have to provide a description."),
image: yup.string()
.matches(
/\.(jpg|png)$/,
"We only support .png or .jpg format files."
)
.required("You have to provide an image.")
});
<Formik
initialValues= {initialValues}
validationSchema = {schema}
>
这是带有 Formik 组件的表单
{({}) => (
<div>
<Form className="form-container">
<Field
className="input-field"
type="text"
name="name"
placeholder="Testimonial title"/>
<ErrorMessage name="name" />
<Field
className="input-field"
type="file"
name="image"
placeholder="Testimonial image"/>
<ErrorMessage name="image" />
<button className="submit-btn" type="submit">Send</button>
</Form>
</div>
)}
</Formik>
这里是react-bootstrap组件(我只更改导入值。)这是那些验证不好的组件。
{({touched, errors}) => (
<div>
<Form className="form-container" onSubmit={onSubmit}>
<Form.Group controlId="name">
<Form.Control
className="input-field"
type="text"
name="name"
isInvalid={name.touched && errors.name}
placeholder="Testimonial title"/>
<Form.Control.Feedback type="invalid">
{errors.name}
</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="image">
<Form.Control
className="input-field"
type="file"
name="image"
isInvalid={image.touched && errors.image}
/>
<Form.Control.Feedback type="invalid">
{errors.image}
</Form.Control.Feedback>
</Form.Group>
<button className="submit-btn" type="submit">Send</button>
{message && <div>{message}</div>}
</Form>
</div>
)}
</Formik>
我像这样初始化引导表单导入:
从react-bootstrap导入{Form as myForm};
然后你可以像这样使用它:
这样它就不会被formik的Form组件覆盖