问题描述
我用antd
的Table
组件,自定义了一个可编辑Table
表单 - antd - 自定义表单控件
问题出现的环境背景及自己尝试过哪些方法
因为自定义表单需要在改动值的时候,调用props.onChange()
现在的问题是,改动值的时机是在TableStore
的columns.render
里面,在那调用不到props.onChange()
我能想到的是把TableStore
的columns.render
改成配置信息,到EditTable
组件内部再复原,可是编辑框要用到columns.render: (text, record, index) =>
的text, record, index
,那又拿不到了
相关代码
下面代码为了方便阅读进行了删减
套一层,用来处理进来的 value
,出去的 props.onChange()
class EditTable extends Component {
constructor(props) {
super(props)
this.state = { value: props.value }
}
componentWillReceiveProps(nextProps) {
if ('value' in nextProps) {
this.setState({ value: nextProps.value })
}
}
render() {
return <Table {...this.props} dataSource={this.state.value} />
}
}
在A组件中使用(注意:整个Table
属于一个FormItem
)
<FormItem>
{getFieldDecorator('list')(
<EditTable {...TableStore.props} />
)}
</FormItem>
Form.create({
onFieldsChange(props, changedFields) {
props.onChange(changedFields)
console.log('onChange')
},
mapPropsToFields(props) {
return props.fields
},
})(A)
props写在一个Store里面了
class TableStore {
@observable.shallow fields = {
list: { value: [] }
};
@computed get props() {
return {
columns: this.columns,
rowKey: 'id',
}
}
@computed get columns() {
return [{
title: 'xx',
dataIndex: 'qty',
render: (text, record) => <Input value={text} onChange={e => this.handleRowChange(record.id, {qty: e.target.value})} />,
}]
}
// 编辑行
@action.bound handleRowChange(rowKey, changedFields) {
let newRows = []
// ....
this.fields.list.value = newRows
}
}
最后图片说明一下自定义表单组件
最后用了另一个思路,在
EditTable
组件内部componentWillReceiveProps
中,判断传入的值是否有变动(PS:这里要用一个新的名称,默认传入的值如果不调用props.onChange
是不会触法componentWillReceiveProps
的)