一、Form操作
- 使用mapPropsToFields和onFieldsChange对form数据进行编辑回显操作
//父组件
constructor(props) {
super();
this.state = {
aInfo: props.section.aInfo, //设置state
};
}
componentWillReceiveProps(nextProps) { //componentWillReceiveProps 在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用
this.setState({
aInfo: nextProps.section.aInfo, //给state设置最新的值
})
}
//将Form变化的Form数据进行state赋值【双向绑定】
handleFormChange = (changedFields) => {
this.state.aInfo[changedFields.name] = changedFields.value;
this.setState(({ aInfo }) => ({
aInfo: { ...aInfo, ...changedFields },
}));
}
//在render里面进行解构
const { aInfo } = this.state;
//给Form组件传值
<SectionForm
aInfo={aInfo}
onChange={this.handleFormChange} //监听Form数据变化
/>
//子组件【Form组件】
Form.create({
name:'sectionForm',
onFieldsChange(props, changedFields) {
//监听Form的值并传值给父组件的onChange
Object.keys(changedFields).forEach(key=>{
props.onChange(changedFields[key]);
})
},
mapPropsToFields(props) {
const { aInfo } = props; //通过父组件传递过来的props获取到值
const dataToForm = (obj)=>{
let formData = {}
for(let [key,value] of Object.entries(obj)){
formData[key] = Form.createFormField({value}) //使用Form.createFormField进行标记【必须】,进行数据回显
}
return formData;
}
return dataToForm(aInfo);
}
})(SectionForm);
- 监听Form值并扔给reducers
//Form组件
componentWillReceiveProps(nextProps) {
this.setState({
aInfo: nextProps.section.aInfo, //监听props更新设置state
});
}
//实时监听Form变化
onChange = () => {
const { dispatch } = this.props;
const { aInfo: formData } = this.state;
dispatch({
type:'section/formData', //扔给reducers
payload:{
formData
}
})
}
//绑定监听事件
<Form onChange={this.onChange}></Form>