简介
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的主要属性:
name
和component
是必须
validate
,rerenderOnEveryChange是一个boolean值
等
(2) props
- FieldArray的props主要有
fields
和meta
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)
网友评论