You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React基于ES2015创建带onClick的动态子组件列表(过滤工具场景)

React ES2015 过滤工具:动态创建带交互的FilterRow组件列表

嘿,我来帮你搞定这个动态过滤行的问题!你现在的需求是组件加载时显示一行过滤选项,点击按钮就能新增带onClick交互的FilterRow子组件,对吧?核心思路是用组件的state来维护所有过滤行的列表,这样就能动态渲染和管理它们了,具体步骤如下:

1. 初始化组件状态

首先在组件的构造函数里,除了现有的newFilter和filterIdCounter,还要新增一个filterRows数组,用来存储所有动态添加的过滤行数据:

constructor(props) {
  super(props);
  this.state = {
    newFilter: {}, // 这里放你的初始过滤数据结构
    filterIdCounter: 1, // 初始行用0,新增从1开始计数
    filterRows: []
  };

  // ES2015里记得绑定方法(或者用类箭头函数替代)
  this.addAnotherFilter = this.addAnotherFilter.bind(this);
  this.handleFilterIdCounter = this.handleFilterIdCounter.bind(this);
  this.updateValue = this.updateValue.bind(this);
  this.updateType = this.updateType.bind(this);
  this.updateOperator = this.updateOperator.bind(this);
}

2. 修改addAnotherFilter方法

原来的方法只是返回单个FilterRow组件,现在我们要把新的过滤行数据加入到filterRows数组中,通过setState更新状态:

addAnotherFilter() {
  this.setState(prevState => ({
    filterRows: [
      ...prevState.filterRows,
      {
        id: prevState.filterIdCounter,
        data: prevState.newFilter
      }
    ],
    filterIdCounter: prevState.filterIdCounter + 1
  }));
}

3. 渲染动态过滤行列表

在render方法里,先渲染初始的过滤行,再遍历filterRows数组渲染所有动态添加的行,最后加上触发添加的按钮:

render() {
  return (
    <div className="filter-container">
      {/* 初始的过滤行 */}
      <FilterRow
        filterData={this.state.newFilter}
        filterId={0}
        handleFilterIdCounter={this.handleFilterIdCounter}
        updateValue={this.updateValue}
        updateType={this.updateType}
        updateOperator={this.updateOperator}
      />
      
      {/* 动态渲染所有新增的过滤行 */}
      {this.state.filterRows.map(row => (
        <FilterRow
          key={row.id} // React列表渲染必须加唯一key
          filterData={row.data}
          filterId={row.id}
          handleFilterIdCounter={this.handleFilterIdCounter}
          updateValue={this.updateValue}
          updateType={this.updateType}
          updateOperator={this.updateOperator}
        />
      ))}

      {/* 添加按钮,点击触发新增逻辑 */}
      <button onClick={this.addAnotherFilter} className="add-filter-btn">
        添加更多过滤条件
      </button>
    </div>
  );
}

可选:添加删除过滤行功能

如果需要支持删除单个过滤行,可以再新增一个方法,然后把它传给每个FilterRow组件:

deleteFilter(filterId) {
  this.setState(prevState => ({
    filterRows: prevState.filterRows.filter(row => row.id !== filterId)
  }));
}

然后在渲染FilterRow的时候加上这个props:

<FilterRow
  // 其他props...
  deleteFilter={this.deleteFilter}
/>

这样你的过滤工具就能完美实现动态添加、管理带交互的过滤行啦!

内容的提问来源于stack exchange,提问作者user42010

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:29:34