React列表动态增加、减少

1,902 阅读1分钟
要实现如下功能:


antd提供了该方法(3x.ant.design/components/…)但是我觉得有些麻烦,不理解的话是很难进行改动的,所以我写了一种更简单的实现方式,代码如下。

class Test extends React.Component {
    constructor(props) {
        super(props)
        this.state={
            list: [{ id: 0, name: '', count: '', type: '' }, { id: 1, name: '', count: '', type: '' }],
            count: 2, // 根据你的需求更改默认数量及默认值
        }
    }
    // 增加一行
    add = () => {
    const { list, count } = this.state;
    const newData = {
      id: count,
      name: '',
      count: '',
      type: '',
    }
    this.setState({
      list: [...list, newData],
      count: count + 1,
    };
  };
  // 删除某一行
  del=(id) => {
    const list = [...this.state.list];
    this.setState({ list: list.filter(item => item.id !== id) });
  }
  // 编辑某行,index指的是索引值
  change=(e, index, name) => {
    const { list } = this.state;
    if (name === 'name') {
      list[index].name = e.target.value
    } else if (name === 'count') {
      list[index].count = e
    } else {
      list[index].type = e
    }
    this.setState({
      list,
    })
  }
  // 样式根据需求自己修改,可用position给添加按钮定位
  render(){
      const { list } = this.state
      return(
          <React.Fragment>
              <Table
                rowKey={record => record.id}
                dataSource={list}
                pagination={false}
                columns={[
                  { dataIndex: 'name', render: (text, record, index) => <Input onChange={e => this.change(e, index, 'name')} value={text || undefined} placeholder="组名称" /> },
                  { dataIndex: 'count', render: (text, record, index) => <InputNumber onChange={e => this.change(e, index, 'count')} value={text || undefined} placeholder="实例数" min={1} /> },
                  { dataIndex: 'type',
                    render: (text, record, index) =>
                      (<Select style={{ width: '120px' }} onChange={e => this.change(e, index, 'type')} value={text || undefined} placeholder="实例用途">
                        <Option value="db">数据库</Option>
                        <Option value="web">Web应用</Option>
                        <Option value="app">APP</Option>
                        <Option value="middleware">中间件</Option>
                        <Option value="k8s">K8S节点</Option>
                       </Select>) },
                  { dataIndex: 'edit', render: (text, record) => <a onClick={() => this.del(record.id)}>{record.id < 2 ? '' : <Icon type="minus-circle" style={{ fontSize: '20px', color: '#4083E7' }} />}</a> },
                ]}
              />
              <Button type="primary" shape="circle" onClick={this.add}>
                <Icon type="plus" />
              </Button>
          </React.Fragment>
      )
  }
}

这是我的实现方式。