首页 > 解决方案 > 如何在 React 中获取单击动态添加的组件的索引并将其删除?

问题描述

我创建了一个自定义组件<Card />。在主页上,我添加了一个按钮,一旦添加了卡片,就会添加这些卡片,每张卡片都有一个特定的删除按钮,该按钮应该从一堆卡片中删除该特定卡片。

这是我的代码:

添加功能添加卡片:

    handleAddComponent() {
    this.setState({
      component: [
        ...this.state.component,
        <Card remove={this.handleRemoveRow} />
      ]
    });
  }

移除卡片移除功能:

    handleRemoveRow(event) {
    // console.log(event.target.);
    this.setState({
      component: this.state.component.slice(0, -1)
    });
  }

和渲染:

    render() {
    return (
      <section>
        {this.state.component}
        <button onClick={this.handleAddComponent}>
          <span>Add</span>
        </button>
      </section>
    );
  }

这段代码的问题是,每当我单击删除按钮时,只有最后一个不符合我条件的组件被删除,我想删除一张特定的卡。component: this.state.component.slice(0, -1)这将删除最后一个组件。

有没有其他方法可以获取每个卡片组件的索引,以便删除特定卡片?

标签: javascriptarraysreactjs

解决方案


 handleAddComponent() {
    this.setState({
      component: [
        ...this.state.component,
        <Card remove={() => this.handleRemoveRow(this.state.component.length)} />
      ]
    });
  }
 handleRemoveRow = i => {
    this.setState({
      component: this.state.component.filter((el, j) => j === i)
    });
  }

推荐阅读