【问题标题】:React delete list of component with button用按钮反应删除组件列表
【发布时间】:2018-11-05 11:52:51
【问题描述】:

我将所有不同的组件插入到数组中,以便最后点击的组件显示在顶部,

但我不知道如何通过在组件内单击按钮来删除项目

似乎我无法在组件内传递带有键索引的函数...

所以我不知道我点击了哪个组件...

请帮我弄清楚。

ComponentA.js
....
render(){
   return <button onClick{this.props.Delete}>Delete</button>
}

Parent.js
const List =({ComponentsList}) =>(
<div> 
ComponentsList.map((item,i) => <div key={i}>{item}</div>)} 
</div>)

此外, 我也发现人们不使用这种方式列出项目,

如果这些组件都不同怎么办?

人们通常会如何处理它?

谢谢!

.

.

.

已编辑:


想出一个关于如何删除组件的问题

请看下面的答案

但我发现状态仍然存在!!!

谁能帮帮我?


【问题讨论】:

    标签: reactjs list components


    【解决方案1】:

    感谢我的朋友,我发现了我的错误。

    也许犯这种明显的错误太愚蠢了,所以我可以在网站上找到答案。

    希望它希望初学者在处理此类问题时需要一些信息。


    父.js

    constructor(props) {
      super(props)
      this.state = {
          listState:[<ComponentB type="AAAA" delete={this.RemoveItem} />, ...]
      }
    }
    
    RemoveItem(dom) {
    dom.currentTarget.parentNode.remove()
    console.log("detect delete")
    }
    
    
    render() {
        const mapToComponent = data => {
          return data.map((contact, i) => {
            return <div>{contact}</div>
          })
        }
    
        return (
          <div className="Graph-Panels">
            {mapToComponent(this.state.PanelState)}
          </div>
        )
      }
    }
    

    【讨论】:

    • 我最终使用过滤器来删除删除组件,仅供参考...,如果有更好的解决方案请告诉我..
    【解决方案2】:

    假设您将子组件保存在一个列表中。您可以在州内拥有它。

    inputList: []
    

    假设父组件上有一个添加子组件的按钮。它的代码看起来与此类似。

    <div>
        <Button variant= "light" className="button" onClick={this.onAddAnotherBtnClick}> 
            Add Another
        </Button>
     {this.state.inputList.map(function(input, index) {
      return input;  
     })}
     </div>
    

    (您可能必须像这样绑定 onAddAnotherBtnClick)。在该州,

    this.onAddAnotherBtnClick = this.onAddAnotherBtnClick.bind(this);
    

    onAddAnotherBtnClick 看起来像这样。

    onAddAnotherBtnClick = (event) =>{
        const inputList = this.state.inputList;
        this.setState({
        inputList: inputList.concat(<ChildComponent Id={inputList.length} 
            callbackDeleteButton={this.delete}/>)
      });
    }
    

    这是删除方法。

    delete = (Id) => {
      delete this.state.inputList[Id];  
      this.setState({ inputList : this.state.inputList });
    }
    

    这是子组件上的删除按钮。

    <Button variant= "light" className="button" onClick={this.onDeleteButtonClick}>
        Delete
    </Button>
    

    这是 onDeleteButtonClick 方法。

    onDeleteButtonClick = () => {
        this.props.callbackDeleteButton(this.state.Id);
    }
    

    (您必须像这样在 State 中绑定方法)。

    this.onDeleteButtonClick = this.onDeleteButtonClick.bind(this);
    

    这里发生的情况是,当每个子组件在道具上创建时,我将 ID 发送给它。当子组件的删除按钮被点击时,它会通过父组件提供的回调方法将其 ID 发送给父组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 2018-03-06
      • 2023-03-24
      • 2016-01-03
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多