栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

Formik官方应用案例解析

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Formik官方应用案例解析

react-select简介

React-Select是github上一个极其火的控件库,星数达到13004,它是React开发中几乎是你必需打交道的一个内容。React Select的基本功能实现的是一个表单中的常见的下拉列表框控件,其实它的功能扩展来看远远不止如此,它支持:

  • 多选
  • 样式定制
  • 多级联动选择
  • 异步加载

    等等。
    但是,如果在你的开发中使用的是一个很基础性的下拉列表框,那么你可以直接使用类似于Semantic UI或者是Material React控件库的Select组件,甚至是最基本的HTML5组件中的那个。

值得注意的是,如如今react-select组件从1.0升级到2.0,变化了巨大变化。有关细节请参考官方网站,总起来看越升级越容易使用,功能也越强大。

在Formik中使用react-select组件

Formik官方也提供了一个使用react-select组件的基本例子,但是使用的是react-select组件的Ver 1.x。在1.x版本时期,组件的样式是使用css方案定义的,但是升级到2.0后,样式使用了更为先进且更迎合React开发思想的Emotion这个开源库(使用JSX组件思想——CSS-in-JS——开发样式)。由于Formik官方提供的相关实例极为简单,所以几需要作两处修改即可。
工程名称:formik-09x-react-select-example,主要文件:index.js
修改后完整代码如下:

import './formik-demo.css';import React from 'react';import { render } from 'react-dom';import { withFormik } from 'formik';//ERROR NOW: import Yup from 'yup';==>changed into the followingimport * as Yup from 'yup';import Select from 'react-select';//NOT SUPPORTED IN VERSION 2.X.// Styles are now implemented with css-in-js rather than less / scss stylesheets//import 'react-select/dist/react-select.css';// Helper styles for demoimport './formik-demo.css';import {    MoreResources,    DisplayFormikState,} from './formik-helper';import SimpleSelect from './SimpleSelect'import AnimatedMulti from './AnimationMultiSelect'const formikEnhancer = withFormik({    mapPropsToValues: props => ({        email: '',        topics: []    }),    validationSchema: Yup.object().shape({        email: Yup.string()            .email('Invalid email address')            .required('Email is required!'),        topics: Yup.array()            .min(3, 'Pick at least 3 tags')            .of(                Yup.object().shape({                    label: Yup.string().required(),                    value: Yup.string().required(),                })            ),    }),    handleSubmit: (values, { setSubmitting }) => {        const payload = {            ...values,            topics: values.topics.map(t => t.value),        };        setTimeout(() => {            alert(JSON.stringify(payload, null, 2));            setSubmitting(false);        }, 1000);    },    displayName: 'MyForm'});const MyForm = props => {  const {    values,    touched,    dirty,    errors,    handleChange,    handleBlur,    handleSubmit,    handleReset,    setFieldValue,    setFieldTouched,    isSubmitting,  } = props;  return (      );};const options = [  { value: 'Food', label: 'Food' },  { value: 'Being Fabulous', label: 'Being Fabulous' },  { value: 'Ken Wheeler', label: 'Ken Wheeler' },  { value: 'ReasonML', label: 'ReasonML' },  { value: 'Unicorns', label: 'Unicorns' },  { value: 'Kittens', label: 'Kittens' },];class MySelect extends React.Component {  handleChange = value => {    // this is going to call setFieldValue and manually update values.topcis    this.props.onChange('topics', value);  };  handleBlur = () => {    // this is going to call setFieldTouched and manually update touched.topcis    this.props.onBlur('topics', true);  };  render() {    return (                        Topics (select at least 3){' '}                        {!!this.props.error &&        this.props.touched && (                      {this.props.error}                  )}          );  }}const MyEnhancedForm = formikEnhancer(MyForm);const App = () => (            Using{' '}              Formik      {' '}      with 3rd-party input components        

      This example shows to use Formik with a 3rd-party      input component. The trick is to use Formik's{' '}      setFieldValue prop and a custom component      class whenever you need a custom change handler.{' '}    

    

      To show this off, below is a Formik-enhanced form. It      has a "vanilla" Formik input for email{' '}      and a custom select component for topics{' '}      that uses Jed Watson's {' '}              react-select      {' '}      library.    

          
            
            
      );render(, document.getElementById('root'));

第一处修改是屏蔽css文件的导入引用,如下:
//import 'react-select/dist/react-select.css';
第二处更为简单,只需要把