Formik是一組react component 和Hook,可以套用在React和React Native,解決了以下問題

  1. 獲取和退出表單狀態的值
  2. 驗證和錯誤消息
  3. 處理表單提交

建立formik表單

// handleChange等同在react表單做了這些
const [values, setValues] = React.useState({});

const handleChange = event => {
  setValues(prevValues => ({
    ...prevValues,
    // we use the name to tell Formik which key of `values` to update
    [event.target.name]: event.target.value
  });
}
import { useFormik } from "formik";

export default (() => {
	const validate = (values) => {
		// 加入正規判斷
		const errors = {}
		if (!values.text) errors.text = "請輸入"
		return errors
	}
	const formik = useFormik({
		// 初始值
		initialValues: { email: " " },
		// 加入驗證功能
		validate,
		// 表單送出功能
	  onSubmit: values => {
			alert(JSON.stringify(values, null, 2));
	  },
	})

	return (
		<form onSubmit={formik.onSubmit}>
			<input 
				name="email"
				value={formik.values.email}
				onChange={formik.handleChange}
			/>
		</form>
	)
})
{formik.touched.text && formik.errors.text ? <div>{formik.errors.text}</div> : null}

不使用useFormik,React上下文傳遞Formik方式(class寫法)

import React from "react";
import { Formik } from "formik";
import * as Yup from "yup";

export default class extends React.Component {
  render() {
    return (
      <Formik
        initialValues={{ phone: "123" }}
        validationSchema={Yup.object({
          phone: Yup.string().min(10, "10位數字").required("請輸入號碼")
        })}
        onSubmit={(values) => {
          console.log(values);
        }}
      >
        {(formik) => (
          <form onSubmit={formik.handleSubmit}>
            <input name="phone" {...formik.getFieldProps("phone")} />
            {formik.errors.phone ? <div>{formik.errors.phone}</div> : null}
            <button type="submit">Submit</button>
          </form>
        )}
      </Formik>
    );
  }
}

validation驗證

validation有兩種方式可以驗證表單

  1. <Formik validate>withFormik({ validate: ... })
  2. <Formik validationSchema>withFormik({ validationSchema: ... })

validate