添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
精彩文章免费看

antd 3.x动态表单 对象数组

补充
编辑的时候要把 id 赋值为list最后一项的id
否则在编辑的时候新添加一条id会重复

官网例子 是单个的

关键点改造

remove = index => {
  const { form } = this.props;
  // 可以使用数据绑定来获取
  const keys = form.getFieldValue('keys');
  const deviceInventory = form.getFieldValue('deviceInventory');
  // 至少有一条
  if (keys.length === 1) {
    return;
  form.setFieldsValue({
    keys: keys.filter((item, key) => key !== index),
    deviceInventory: deviceInventory.filter((item, key) => key !== index),
add = () => {
  const { form } = this.props;
  // 可以使用数据绑定来获取
  const keys = form.getFieldValue('keys');
  console.log(id, '添加一条', keys);
  id++;
  const nextKeys = keys.concat({
  console.log(id, '完成', nextKeys);
  form.setFieldsValue(
      keys: nextKeys,
    () => {
      console.log('获取数组值', form.getFieldValue('deviceInventory'));
deviceInventory list没有id
keys 只有id
合并后编辑就不会有问题了

let deviceInventory = [];
deviceInventory = fieldsValue.keys.reduce((total, item, index, arr) => {
  total.push({
    ...item,
    ...fieldsValue.deviceInventory[index],
  return total;
}, []);
getFieldDecorator('keys', {
  initialValue: this.state.form.deviceInventory,
const keys = getFieldValue('keys');
const formItems = keys.map((k, index) => (
    <Row gutter={24} key={k.id}>
      <Col span={7}>
        <Form.Item label={'名称'} required={false}>
          {getFieldDecorator(`deviceInventory[${index}].deviceName`, {
            initialValue: k.deviceName,
            rules: [
                required: true,
                message: '请输入名称',
                max: 15,
                message: '输入超过限制',
          })(<Input placeholder="请输入名称" disabled={this.state.isDisabled} />)}
        </Form.Item>
      <Col span={7}>
        <Form.Item label={'数量'} required={false}>
          {getFieldDecorator(`deviceInventory[${index}].deviceNum`, {
            initialValue: k.deviceNum,
            rules: [
                required: true,
                message: '请输入数量',
                max: 9,
                message: '输入超过限制',
            <Input placeholder="请输入数量" disabled={this.state.isDisabled} />
        </Form.Item>
      {keys.length > 1 ? (
        <Col span={3}>
          <Form.Item>
              className="dynamic-delete-button"
              type="minus-circle-o"
              onClick={() => this.remove(index)}
          </Form.Item>
      ) : null}

参考: https://gitee.com/hope93/antd-form1

最后编辑于:2020-09-03 09:19