antd 自定义表单,实现一个可编辑Table通用表单组件
问题描述
我用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
}
}
最后图片说明一下自定义表单组件
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你把onchange事件放到props里面传过去不久行了
最后用了另一个思路,在
EditTable
组件内部componentWillReceiveProps
中,判断传入的值是否有变动(PS:这里要用一个新的名称,默认传入的值如果不调用props.onChange
是不会触法componentWillReceiveProps
的)你在column里面每一项的render不是会渲染一个Input组件吗,在Input组件change的时候可以调用props.onChange,然后在表单域中,你当前Table的表单域名是'list,然后你可以通过getFieldsValue('list')获取到你传过来的值;