【问题标题】:how to pass the current item to the function so that i can remove it from array in react component?如何将当前项目传递给函数,以便我可以从反应组件的数组中删除它?
【发布时间】:2018-09-01 18:40:17
【问题描述】:

我只是不能在函数中传递当前项目,因为我在“X”中有一个点击事件,这是一个不同的节点,所以我总是将项目作为 X 传递,而不是数组中的项目。我在考虑把它变成一个不同的组件并导入它,但我只是想看看我这里有没有东西,我将如何删除。所以我的主要问题是如何传递数组中的当前项。这是我的代码

export default class App extends Component {
constructor(props) {
    super(props)
    this.state = {
        fruits: ["apple", "orange", "mango", "banana"],
        name: "Micheal"
    }
    // this.handleClick = this.handleClick.bind(this);

}

delItem(item) {
    console.log('Click happened');
    console.log(item)
    //console.log(item.target.innerText) //x
    console.log(this.state.fruits)
    var newList = this.state.fruits.filter(val => {
        return item != val
    })
    console.log(newList);
    // this.setState({
    //     fruits : newList
    // })

}

render() {
    var fruitsList = this.state.fruits.map(item => {
        return (
            <li>
                <h1> {item} </h1>
                <p className="del-btn" onClick={this.delItem.bind(this)}> x </p>
            </li>
        )
    })

    return (
        <div>
            <div>
                <h1> Hello {this.state.name} from inside a component </h1>
                <About></About>
            </div>
            <div>
                <ul>
                    {fruitsList}
                </ul>
            </div>
        </div>
    )
 }
}


render(<App name="Milan" />, document.getElementById('app'));

【问题讨论】:

  • onClick={this.delItem.bind(this, item)}
  • 天哪,非常感谢,我在最后的处理事件文档中错过了这一点。

标签: reactjs react-component


【解决方案1】:

嗯,你可以选择直接在函数onClick中发送item ref - this.delItem.bind(this, item)

delItem(item) {
   let fruits= this.state.fruits;

   function findFruit(element, index, array){
        return element==item;
   }

   let index = fruits.findIndex(findFruit);
   fruits.splice(index,1);
   this.setState({fruits : fruits});
}

【讨论】:

    【解决方案2】:

    将您的 delItem 函数更改为更高阶...您可以让 delItem() 成为返回函数的函数,并且该函数可以使用传递给 delItem() 函数的参数...传递果实!

    delItem = (fruit) => () => {
      console.log('Click happened');
      console.log(item)
    
      // delete your fruit
    }
    

    然后绑定onClick如下:

    <p className="del-btn" onClick={this.delItem(item)}> x </p>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 2017-12-30
      相关资源
      最近更新 更多