我想使用ant design在按下按钮后动态添加2个文本框,并将其存储在数组中,如何实现?

时间:2019-07-19 11:16:11

标签: react-hooks antd

enter image description here我想在使用蚂蚁设计按下按钮后动态添加2个文本框,如图中所示,还用(减号)按钮删除文本框,将这些数据存储在数组initialState中,我该如何实现?

https://codesandbox.io/s/blissful-leakey-qzp8o

import ReactDOM from "react-dom";
import "antd/dist/antd.css";    
import { Form, Input, Button } from "antd";

function DualInput({form}) {
  const {getFieldDecorator} = form 
  const initialState = []

  const handleSubmit = (e) => {
    form.validateFieldsAndScroll((err , field) => {           
      initialState.push(field)     
      console.log(initialState)
    }
    )}

    const handleAdd = () => {

    }

    const handleMinus = () => {

    }
  return <div>
    <Form layout="inline" >
    <Form.Item label="Quantity">
  {getFieldDecorator("quantity", {
    rules: []
  })(<Input placeholder="Quantity" size="large" />)}
    </Form.Item>
    <Form.Item label="Price">
      {getFieldDecorator("price", {
        rules: []
      })(<Input placeholder="Price" size="large" />)}
      </Form.Item>
      <Form.Item>
      <Button type="secondary" shape="circle" icon="plus" size="large" onClick={handleAdd}/>
      </Form.Item>
      <Form.Item>
      <Button type="secondary" shape="circle" icon="minus" size="large" onClick={handleMinus}/>
      </Form.Item>
      <Form.Item>
      <Button type="secondary" size="large" onClick={handleSubmit}>Submit</Button>
      </Form.Item>
    </Form>
</div>;
}
const DualInput2 = Form.create()(DualInput);
ReactDOM.render(<DualInput2 />, document.getElementById("container"));

我要获取的数组(样本):

const initialState = [{Quantity: "100", price: "100"}, {Quantity: "200", price: "200"}]

2 个答案:

答案 0 :(得分:0)

将此功能组件更改为类组件。并通过添加两个条目来更新状态(数组),您需要每次单击添加两个新条目以添加按钮。

通过呈现与数组长度一样多的formItem,您将获得正确数量的fromItem。

答案 1 :(得分:0)

您有an offical example的操作方式。

remove = k => {
  const { form } = this.props;
  // can use data-binding to get
  const keys = form.getFieldValue("keys");
  // We need at least one passenger
  if (keys.length === 1) {
    return;
  }

  // can use data-binding to set
  form.setFieldsValue({
    keys: keys.filter(key => key !== k)
  });
};

add = () => {
  const { form } = this.props;
  // can use data-binding to get
  const keys = form.getFieldValue("keys");
  const nextKeys = keys.concat(id++);
  // can use data-binding to set
  // important! notify form to detect changes
  form.setFieldsValue({
    keys: nextKeys
  });
};