Formik 总结

Submitted by Lizhe on Thu, 06/14/2018 - 09:44

以下内容总结自Formik的官方文档, 所以你会看到一些原文引用(当然是我过滤后的)

Overview

Formik 总的来说帮助我们做下面3件事

  1. Getting values in and out of form state
  2. Validation and error messages
  3. Handling form submission

 

Why not Redux-Form?

总的来说, redux form提供的东西太重了, 过多的reducer, 而且通常情况下我的Form值并不需要保存在redux的state中

My goal with Formik was to create a scalable, performant, form helper with a minimal API that does the really really annoying stuff and leaves the rest up to you.

 

Formik 使用以下3个event handlers

handleChange, handleBlur, and handleSubmit 

handleChange and handleBlur work exactly as expected--they use a name or id attribute to figure out which field to update.

也就是说Formik需要使用name或者是id来确认是哪个field被change了

以下两种方式使用Formik都是可以的

There are two ways to use Formik:

  • withFormik(): A Higher-order Component (HoC) that accepts a configuration object
  • <Formik />: A React component with a render prop

 

正常来说你可以使用下面这些常用属性

  values,

  errors,

  touched,

  handleChange,

  handleBlur,

  handleSubmit,

  isSubmitting,

 

如果你向我一样, 想传入一些自定义的变量, 你可要看仔细了

自定义的form应该是这样的

import React from "react";

import Alert from "./Alert";

 

const PlayerForm = ({

values,

handleSubmit,

iWantTransferthisValue

}) => {

console.log("here:")

console.log(iWantTransferthisValue)

return (

<form className="form" onSubmit={handleSubmit}>

{iWantTransferthisValue}

</form>

);

};

 

export default PlayerForm;

 

下面是对上面form的调用

const EditPlayerForm = props => <PlayerForm {...props} isNewPlayer={false} iWantTransferthisValue={props.wantedValue}/>;

<Formik onSubmit={onSubmit} initialValues={player} iWantTransferthisValue="testValue">

            {x => <EditPlayerForm {...x} iWantTransferthisValue={'great!'} /> }

</Formik>

 

submit方法接收两个参

第一个是values, 保存form的值, 第二个参数是扩展参数, 这里用结构拆开, 包含了一些回调函数

const onSubmit = async (values, { props, setSubmitting, setErrors }) => {
    await api.edit(values).then(
      values => {
        console.log(values),
        setSubmitting(false),
        history.push("/players")
      },
      error => {
        setSubmitting(false);
        setErrors({ general: error.message });
      });
  };

 

如果使用Field 标签, 还可以写的更简单一些, 下面的input标签和Field标签等价


 

<input

              type="text"

              name="social.facebook"

              onChange={handleChange}

              onBlur={handleBlur}

              value={values.social.facebook}

/>


 

<Form>

            <Field type="email" name="email" />

</Form>

 

如果需要给form中的fileds赋初始值


 

<Formik

      initialValues={{ name: 'jared' }}

</Formik>