2016-10-31 16:33:25 +08:00
---
order: 8
title:
zh-CN: 表单数据存储于上层组件
en-US: Store Form Data into Upper Component
---
## zh-CN
2017-03-01 18:44:59 +08:00
通过使用 `onFieldsChange` 与 `mapPropsToFields` ,可以把表单的数据存储到上层组件或者 [Redux ](https://github.com/reactjs/redux )、[dva](https://github.com/dvajs/dva) 中,更多可参考 [rc-form 示例 ](http://react-component.github.io/form/examples/redux.html )。
2016-10-31 16:33:25 +08:00
2017-11-17 21:19:10 +08:00
**注意:**`mapPropsToFields` 里面返回的表单域数据必须使用 `Form.createFormField` 包装。
2016-10-31 16:33:25 +08:00
## en-US
2017-03-01 18:44:59 +08:00
We can store form data into upper component or [Redux ](https://github.com/reactjs/redux ) or [dva ](https://github.com/dvajs/dva ) by using `onFieldsChange` and `mapPropsToFields` , see more at this [rc-form demo ](http://react-component.github.io/form/examples/redux.html ).
2016-10-31 16:33:25 +08:00
2017-11-17 21:19:10 +08:00
**Note:** You must wrap field data with `Form.createFormField` in `mapPropsToFields` .
2017-02-13 10:55:53 +08:00
````jsx
2016-10-31 16:33:25 +08:00
import { Form, Input } from 'antd';
2018-06-27 15:55:04 +08:00
2016-10-31 16:33:25 +08:00
const FormItem = Form.Item;
const CustomizedForm = Form.create({
2016-11-02 10:47:50 +08:00
onFieldsChange(props, changedFields) {
props.onChange(changedFields);
2016-10-31 16:33:25 +08:00
},
mapPropsToFields(props) {
return {
2017-11-17 21:19:10 +08:00
username: Form.createFormField({
2016-10-31 16:33:25 +08:00
...props.username,
2017-09-13 18:03:56 +08:00
value: props.username.value,
2017-11-17 21:19:10 +08:00
}),
2016-10-31 16:33:25 +08:00
};
},
2017-01-09 17:40:01 +08:00
onValuesChange(_, values) {
console.log(values);
},
2016-10-31 16:33:25 +08:00
})((props) => {
const { getFieldDecorator } = props.form;
return (
2017-03-02 10:49:06 +08:00
< Form layout = "inline" >
2016-10-31 16:33:25 +08:00
< FormItem label = "Username" >
{getFieldDecorator('username', {
rules: [{ required: true, message: 'Username is required!' }],
})(< Input / > )}
< / FormItem >
< / Form >
);
});
2017-02-20 11:50:57 +08:00
class Demo extends React.Component {
state = {
fields: {
username: {
value: 'benjycui',
2016-10-31 16:33:25 +08:00
},
2017-02-20 11:50:57 +08:00
},
};
2018-06-27 15:55:04 +08:00
2017-02-20 11:50:57 +08:00
handleFormChange = (changedFields) => {
2018-03-26 15:41:42 +08:00
this.setState(({ fields }) => ({
fields: { ...fields, ...changedFields },
}));
2017-02-20 11:50:57 +08:00
}
2018-06-27 15:55:04 +08:00
2016-10-31 16:33:25 +08:00
render() {
const fields = this.state.fields;
return (
< div >
< CustomizedForm { . . . fields } onChange = {this.handleFormChange} / >
< pre className = "language-bash" >
{JSON.stringify(fields, null, 2)}
< / pre >
< / div >
);
2017-02-20 11:50:57 +08:00
}
}
2016-10-31 16:33:25 +08:00
ReactDOM.render(< Demo / > , mountNode);
````
< style >
#components-form-demo-global-state .language-bash {
max-width: 400px;
border-radius: 6px;
margin-top: 24px;
}
< / style >