redux-form学习笔记

首先要根据 formReducer 绑定到项目的 store 里面:

1
2
3
4
5
6
7
8
9
import { createStore, combineReducers } from 'redux'
import { reducer as formReducer } from 'redux-form'

const rootReducer = combineReducers({
..., // 其他的 reducer
form: formReducer // 必须把 formReducer对应到 form 键
})

const store = createStore(rootReducer)

然后在组件中引用 redux-form 相关组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React from 'react'
import { Field, reduxForm } from 'redux-form'
// 组件
const ContactFormComponent = props => {
const { handleSubmit } = props
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">姓名</label>
<Field name="name" component="input" type="text" />
</div>
<div>
<label htmlFor="email">邮箱</label>
<Field name="email" component="input" type="email" />
</div>
<button type="submit">提交</button>
</form>
)
}

const ContactForm = reduxForm({
form: 'contact' // 起一个唯一的名字
})(ContactFormComponent)

export default ContactForm

然后调用:

1
2
3
4
5
6
7
8
9
10
11
import React from 'react'
import ContactForm from './ContactForm'

class ContactPage extends React.Component {
submit = values => {
console.log(values) // 打印用户在表单输入的值
}
render() {
return <ContactForm onSubmit={this.submit} />
}
}

有时候,我们需要在组件中获取表单中用户输入的值,需要通过 formvalueselector 来放到 this.props 中,例如获取注册表单中用户输入的电话号码:

1
2
3
4
5
6
7
8
9
10
const selector = formValueSelector('register_form')

export default withRouter(
connect(
state => ({ telephone: selector(state, 'telephone') })
)(reduxForm({
form: 'register_form',
validate
})(RegisterForm))
)

还有些时候,我们想在点击某个按钮的时候,触发某个字段进行有效性验证,可以用 blur 来手动触发验证:

1
2
3
4
5
const { blur, telephone } = this.props
if (!isPhone(telephone)) {
blur('telephone')
return
}