Redux-Form

简介

redux-form主要用于管理reudx中的form表单数据

主要模块

(1) formReducer reducer

formReducer是form表单的reducer,表单的各种操作以 Redux action 的方式,通过此 reducer 来促使 Redux store 数据的变化。

store.js


import { reducer as formReducer } from 'redux-form'    // 引入redux-form的 reducer模块



const store = createStore(
    combineReducers({
        user,
        form: formReducer,       // 使用,注意这里的form属性最好写成form,不要用其他名字
    }),
    window.devToolsExtension ? window.devToolsExtension() : undefined,
    applyMiddleware(sagaMiddleware)
)

(2) reduxForm()方法

让用reduxForm装饰的组件拥有form state和一些表单方法。

username.js


import React from 'react';
import {Field, reduxForm} from 'redux-form';     // 引入reduxForm()方法,和 Field组件

const fieldGo = (props) => {
    console.log(props, 'props')
        return(
            <div>
                <input type="text" />
            </div>
        )
}

class usenName extends React.Component {
    
    componentDidMount() {
        console.log(this.props, 'this.props')
    }
    go = () => {
        this.props.getusername(11,12,13);
        this.props.getsaga();
    }
    render() {
        return (                                   // redux-form的Field组件
                <Field                                  
                    name="FieldUserOne"
                    type="text"
                    component={fieldGo}
                >
                </Field>
            </div>
        )
    }
}

export default reduxForm({                          // 使用reduxForm()方法
    form: 'testReduxForm',                          // 该表单的名字
})(usenName);

(3) Field 等组件 --- 最简单的组件

用Field代替原本的 <input/> 组件,可以与redux-form的逻辑相连接。
·
·
·
·
·


(一) reduxForm

reduxForm的配置项

(1) form : String ------------------------- 必须

  • the name of your form and the key to where your form's state will be mounted under the redux-form reducer
  • form的名字,并且作为挂载到redux-form reducer中的key

(2) initialValues : Object<String, String> ---------------- 初始值

  • The values with which to initialize your form in componentWillMount(). The values should be in the form { field1: 'value1', field2: 'value2' }.
  • form中state的初始值, 在componentWillMount()时被挂载

(3) validate : (values:Object, props:Object) => errors:Object

  • a synchronous validation function that takes the form values and props passed into your component. If validation passes, it should return {}. If validation fails, it should return the validation errors in the form { field1: <String>, field2: <String> }. Defaults to (values, props) => ({}).
  • validate同步验证,values是用户输入的值,如果通过验证,需要返回一个空对象,如果未通过验证,返回错误信息。错误信息是一个对象(属性名是Field的name值,属性的值是错误信息)
export default reduxForm({
    form: 'user-name',
    initialValues:{selectOne: 'two'},
    validate:(value, props) => {               // reduxForm的validate属性,是一个函数
        if(!value.user) {
            return {user: 'user不能为空'}
        } else {
            return {}
        }
    }
})(userNameComponent)

·

reduxForm传给包装的组件的props

(1) handleSubmit -------------------------------- ( 重要 )

handleSubmit(eventOrSubmit) : Function

  • A function meant to be passed to <form onSubmit={handleSubmit}> or to <button onClick={handleSubmit}>. It will run validation, both sync and async, and, if the form is valid, it will call this.props.onSubmit(data) with the contents of the form data.

  • handleSubmit 在 <form onSubmit={ handleSubmit}>或者<button onClick={handleSubmit}> 使用,在form表单通过同步或者异步验证后,就会触发handleSubmit(data => ...)事件,会把表单的各项值作为回调函数的参数

  • 提交表单案列:




import React from 'react';
import {reduxForm, Field, FieldArray, Form  } from 'redux-form';      // 引入 Form


class userNameComponent extends React.Component {   
    render() {
        return (
            <div>      // Form中有onSubmit属性, 这里的data就是提交的表单的值
                <Form onSubmit={this.props.handleSubmit(data => console.log(data))} >
                    <div>
                        <FieldArray
                            name="field-array"
                            component={this.createFieldArray}
                        ></FieldArray>
                    </div>
                    <br/>
                    <div>
                        姓名:<Field name='initialValues' component='input'></Field>
                    </div>
                    <button type="submit">submit</button>  
                </Form>
                <br/>
            </div>
        )   
    }
}

export default reduxForm({    // reduxForm包装的组件的props中有 handleSubmit 属性
    form: 'user-name',
    initialValues: {initialValues: '马云',},
})(userNameComponent)




 // 除了用Form的onsubmit函数来触发,还可以给按钮添加事件来触发,不过,onSubmit包括点击,键盘事件等

 // <button onClick={this.props.handleSubmit(data => ...)}>提交</button> 不支持键盘事件




(二) Field 组件

Field组件必须有的属性是 name,component

(1) name属性 ------------------------------- 必须

  • name属性是一个 string
  • 注意 name属性不能是数字型的字符串,因为它们会混淆array indexes
    e.g: name="42" or name="foo.5.email" , ( e.g是例如的意思 )

(2) component属性 ----------------------- 必须

  • component属性可以是 component,stateless function,string 三种
  • stateless function 是无状态组件的意思

(3) format属性

  • format属性是一个函数:(value, name) => formattedValue
  • value 是从store获得要显示在Field input种的数据name是Field组件的name属性的值
  • 常用的情况是将数字格式化为货币 或 将日期格式化为本地化的日期格式。

(4) normalize属性

  • normalize属性是一个函数
  • normailze属性的作用是:将用户输入的值,转换成你想存入store中 field字段的值
    e.g: 将输入的小写字符转换成大写,存入store
  • (value, previousValue, allValues, previousAllValues) => nextValue
  • value 是用户输入的值previousValue是用户上一次输入的值,改变前的值
  • allValues是一个对象previousAllValues是一个对象
(5) onBlur属性
  • onBlur属性是一个函数
  • (event, newValue, previousValue, name) => void
  • event 是blur事件函数
  • newValue是onBlur事件触发时的value值
  • name是该feild的name属性的值
  • 注意:
    当 event参数 的 event.preventDefault()事件触发时,这个blur action 不会被dispatch,并且 value 和 focus state 不会在 redux 中更新


    event.preventDefault() -- 导致不会dispatch blur action,并且 focus 的state也不会更新

(6) onChange属性

  • (event, newValue, previousValue, name) => void
  • A callback that will be called whenever an onChange event is fired from the underlying input. If you call event.preventDefault(), the CHANGE action will NOT be dispatched, and the value will not be updated in the Redux store.
  • 和 onBlur属性一样,onChange属性的回掉函数在 inpurt框 onChage事件发生时,被触发
  • 注意:
    如果参数的 event 的 event.preventDefault()事件触发时,CHANGE action 不会被 dispatch, 并且 value 不会在 store中更新

(7) onFocus属性

  • onFocus : (event, name) => void
  • A callback that will be called whenever an onFocus event is fired from the underlying input. If you call event.preventDefault(), the FOCUS action will NOT be dispatched, and the focus state will not be updated in the Redux store.

(8) props属性

  • props属性是一个对象 e.g: props={{'age': 20}}
  • props属性定制的对象,通过Field的component属性,传递给 component 组件。会融合自身的props






import React from 'react';

import {reduxForm, Field} from 'redux-form';

const goFieldComponent = (props) => {
    console.log(props, 'input ---- props7777777777777777777')
    return (
        <input type="text" placeholder="请输入用户名" {...props.input} />
    )
}
class userNameComponent extends React.Component {
    componentDidMount() {
        console.log(this.props)
    }
    render() {
        return (
            <div style={{background:'silver', padding: '30px'}}>
                这是username组件
                <br/>
                <div>
                    <span>用户名</span>
                    <Field
                        name="username"
                        component={goFieldComponent}
                        // component="input"
                        format= {(value, name) => { return value ? value.toUpperCase() : ''}}
                        normalize={(value, previousValue, allValues, previousAllValues ) => {
                            console.log(allValues,'normalize-----allValues')
                            return value.toUpperCase()
                        }}
                        onBlur={(event, newValue, previousValue, name) => {
                            event.preventDefault();
                            console.log(event, 'event');
                            console.log(newValue, 'newValue');
                            console.log(previousValue, 'previousValue');
                            console.log(name, 'name');
                        }}
                        props={{'age': 20}}
                        customAttribute={'this is custom attribute provide to component'}
                    ></Field>
                </div>
            </div>
        )
    }
}

export default reduxForm({
    form: 'user-name'
})(userNameComponent)



props

Props

  • field的props主要被分割为 input 和 meta
  • Any custom props passed to Field will be merged into the props object on the same level as the input and meta objects. 所有自定义的props 都会被合并到props对象,并且和input,meta同级

Input Props

(1) input.name : String
  • When nested in FormSection, returns the name prop prefixed with the FormSection name. Otherwise, returns the name prop that you passed in.
  • 当嵌套在FormSection时,返回的是FormSection name的前缀,否则,返回Field的name属性值
(2) input.value: any
  • The value of this form field.
  • input.value的值,是从Field得到的用户输入的值,可以是boolean,string,checkbox,或者其他input的type类型。如果没有值,则是‘’空字符串

Meta Props

(1) meta.initial : any ----------------------------------- field 的初始值
  • The initial value of the field.
(2) meta.form : String ------------------------------ form表单的name值
  • The name of the form. Could be useful if you want to manually dispatch actions.
  • meta.form的值时form表达的name值,在手动 dispatch action 很有作用
(3) meta.error : String -------------------------------(重要)
  • The error for this field if its value is not passing validation. Both synchronous, asynchronous, and submit validation errors will be reported here.
  • meta.error属性的值是:在未通过同步验证,异步验证,提交验证的错误信息
(4) meta.dispatch : Function ----------------------- dispatch()
  • The Redux dispatch function.
const goFieldComponent = (props) => {
    console.log(props, 'input ---- props7777777777777777777')
    props.meta.dispatch({
        type: 'GET_NAME',
        payload: 'woowwu'
    });
    return (
        <input type="text" placeholder="请输入用户名" {...props.input} />
    )
}
  • meta.error的值是 同步验证,异步验证,和 submit验证未通过时,抛出的错误信息
(5) meta.active : boolean ---------------------------- focus (true)
  • true if this field currently has focus. It will only work if you are passing onFocus to your input element.
  • meta.active是一个布尔值,在field获得焦点时meta.active值为true,其他时候为false
(6) meta.dirty : boolean ------------------------------ change (true)
  • true if the field value has changed from its initialized value. Opposite of pristine.
  • meta.dirty当field value 改变时,值为true
  • dirty是肮脏的的意思
  • pristine是原始状态的意思
  • opposite是相反的意思
(7) meta.pristine : boolean -------------------------- change (false)
  • true if the field value is the same as its initialized value. Opposite of dirty.
  • meta.pristine在field value 和 initial value 相同时为true
(8) meta.visited: boolean -----------------------只要获得过焦点,就为true
  • true if this field has ever had focus. It will only work if you are passing onFocus to your input element.
  • 获得过焦点为true,页面初始状态下,从未获得焦点过,为false
(9) meta.submitting : boolean
  • true if the field is currently being submitted
(10) meta.valid : boolean
  • true if the field value passes validation (has no validation errors). Opposite of invalid.

Field例子

//select


import React from 'react';

import {reduxForm, Field} from 'redux-form';
import {Select} from 'antd';
const Option = Select.Option;


class userNameComponent extends React.Component {

    getSelect = ({input, meta, ...rest}) => {
        return (
            <Select style={{ width: 120 }} {...input} {...meta}>     // input对象中有value属性
                <Option value="two">星期二</Option>
                <Option value="thr">星期三</Option>
                <Option value="for">星期四</Option>
                <Option value="fiv">星期五</Option>
            </Select>
        )
    }
    getInput = ({input, meta}) => {
        console.log(meta.error)
        return (
            <div>
                <input type="text" {...input} />
                {meta.error}                       // 显示validate未通过验证的错误信息
            </div>
            
        )
    }
    render() {
        return (
            <div style={{background:'silver', padding: '30px'}}>
                <div>                               
                    <Field             
                        name="selectOne"
                        component={this.getSelect}       
                        props={{value:'two'}}  
                    ></Field>                      // name 和 component 为必须字段
                    
                     <Field name="user" component={this.getInput}></Field>
                </div>
            </div>
        )
    }
}

export default reduxForm({                 // reduxForm包装组件
    form: 'user-name',                     // 该表单的名字是 ‘user-name’
    initialValues:{selectOne: 'two'}       // form表单初始值设置, Field selectOne 的初始值是‘two’
    validate:(value, props) => {           // 同步验证,return的对象在props的 meta属性中
        if(!value.user) {
            return {user: 'user不能为空'}
        } else {
            return {}
        }
    }    
})(userNameComponent)

·
·
·
·
·


(三) FieldArray

(1) 主要属性

  • FieldArray的主要属性:
    namecomponent 是必须
    validatererenderOnEveryChange是一个boolean值

(2) props

  • FieldArray的props主要有 fieldsmeta

fields

(1) fields.name
  • When nested in FormSection, returns the name prop prefixed with the FormSection name. Otherwise, returns the name prop that you passed in.
  • 当嵌套在FormSection中时,fields.name返回的时FormSection的name属性。否则返回FieldArray的name值
(2) fields.forEach(callback) : Function
  • A method to iterate over each value of the array
  • 遍历数组中的每个值
(3) fields.get(index) : Function
  • A method to get a single value from the array value.
  • 得到数组中的单个值,对应下标的单个值
(4) fields.getAll() : Function
  • 得到数组中的每个值
(5) fields.length : Number
  • FieldArray的数组的长度
(6) fields.map(callback) ------------------------------ (重要)
  • map循环
(7) fields.move(from:Integer, to:Integer) : Function
  • Moves an element from one index in the array to another.
  • 注意 from 和 to 都是 index
(8) fields.pop()fields.push(value:Any)fields.remove(index:Integer)fields.removeAll()fields.shift()fields.unshift(value:Any)fields.swap(indexA:Integer, indexB:Integer) 对换位置

meta

  • 和属性field的props的meta一样

FieldArray实例:

// FieldArray实例   ------------ 添加,删除,嵌套


import React from 'react';
import {reduxForm, Field, FieldArray} from 'redux-form';



class userNameComponent extends React.Component {

    addMessage = (props) =>  {
        return (
            <div>
                <button onClick={() => props.fields.push({})} >添加信息</button>
                {
                    props.fields.map( (field2, index2)  => (
                    <div key={index2}>
                            爱好:<Field name={`${field2}-add`} component="input"></Field>
                    </div>
                    ))
                }
            </div>
        )
    }
    
createFieldArray = ({fields, meta}) => {
    return (
        <div>                                                                 // fields.push()
            <button onClick={() => fields.push({})}>添加个人信息表单</button>  
            <div>
            {
                fields.map( (field, index)  => {                              // feilds.map()
                    return (
                        <div key={index}>
                            姓名:<Field name={`${field}-name`} component="input"></Field>
                            <br/>
                            年龄:<Field name={`${field}-age`} component="input"></Field>
                            <br/>
                            爱好:<Field name={`${field}-hobby`} component="input"></Field>
                            <div>                                           // 里层的FielsArray
                               <FieldArray                                 
                                   name={`${field}-addHobby`} 
                                   omponent={this.addMessage}>
                               </FieldArray> 
                            </div>
                            <div 
                               style={{position: 'relative', left:'300px'}} 
                               onClick={() => fields.remove(index)}     // fields.remove(index)
                             >
                               <button>删除表单</button> 
                            </div>
                        </div>
                    )
                })
            }
            </div>
        </div>
    )
}

    render() {
        return (
           <div>                                                          // 第一个 FieldArray
               <FieldArray                              
                name="field-array"
                component={this.createFieldArray}
               ></FieldArray>
           </div>
        )   
    }
}

export default reduxForm({
    form: 'user-name',
})(userNameComponent)


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,783评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,360评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,942评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,507评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,324评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,299评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,685评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,358评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,652评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,704评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,465评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,318评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,711评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,991评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,265评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,661评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,864评论 2 335

推荐阅读更多精彩内容