2

我阅读了这个解决方案,但这并没有真正回答这个问题。我正在使用 formik 和语义 UI 反应。是否可以将 Yup 与语义 UI 反应一起使用?如果是的话,有人可以提供一个例子吗?

4

1 回答 1

6

是的,这是可能的,这是一种方法。将此代码粘贴到 codesandbox.io 并安装依赖项,例如 formik yup 和 semantic-ui-react

import React from "react";
import { render } from "react-dom";
import { Formik, Field } from "formik";
import * as yup from "yup";
import { Button, Checkbox, Form } from "semantic-ui-react";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};

const App = () => (
  <>
    <Formik
      initialValues={{
        firstname: "",
        lastname: ""
      }}
      onSubmit={values => {
        alert(JSON.stringify(values));
      }}
      validationSchema={yup.object().shape({
        firstname: yup.string().required("This field is required"),
        lastname: yup.string().required()
      })}
      render={({
        values,
        errors,
        touched,
        handleChange,
        handleBlur,
        handleSubmit
      }) => {
        return (
          <Form>
            <Form.Field>
              <label>First Name</label>
              <input
                placeholder="First Name"
                name="firstname"
                onChange={handleChange}
                onBlur={handleBlur}
              />
            </Form.Field>
            {touched.firstname && errors.firstname && (
              <div> {errors.firstname}</div>
            )}
            <Form.Field>
              <label>Last Name</label>
              <input
                placeholder="Last Name"
                name="lastname"
                onChange={handleChange}
                onBlur={handleBlur}
              />
            </Form.Field>
            {touched.lastname && errors.lastname && (
              <div> {errors.lastname}</div>
            )}
            <Form.Field>
              <Checkbox label="I agree to the Terms and Conditions" />
            </Form.Field>
            <Button type="submit" onClick={handleSubmit}>
              Submit
            </Button>
          </Form>
        );
      }}
    />
  </>
);

render(<App />, document.getElementById("root"));
于 2019-04-05T05:16:28.783 回答