简体   繁体   English

在React中将函数传递给子级

[英]Passing function to child in React

I'd like to pass functions to the child using props, and create several components that can be clicked on 我想使用道具将函数传递给孩子,并创建几个可以单击的组件

parent class: 家长班:

handleClick(i){
    alert(i);
}

render(){
    var items = [];
    for (var i = 0; i < 7; i++) {
      items.push(
        <Item onClick={()=>this.handleClick(i)} />
      );
    }
    return <ul>{items}</ul>;
}

child class: 子班:

render() {
    return (
      <li onClick={this.props.onClick}> some names </li>
    );
}

But the result is different from what I expected. 但是结果与我预期的不同。

I wanted the first element to alert(0) , the second element to alert(1) , and so on. 我希望第一个元素为alert(0) ,第二个元素为alert(1) ,依此类推。

But instead, all elements shows 7 when I click on them. 但是,当我单击它们时,所有元素都显示7 I guess that's because I'm always using the i after for-loop has finished. 我猜那是因为for循环完成后我总是使用i

I guess this is a problem about basic concepts of scopes or using closure or something, rather than a React problem. 我猜这是关于范围的基本概念或使用闭包之类的问题,而不是React问题。 But still I can't find a right way to fix this problem. 但是我仍然找不到解决此问题的正确方法。

It happens because of closure, since your are using var keyword for forLoop iterator, its scope will be the render function and the value passed to handleClick will always be the updated value of iterator. 由于关闭而发生这种情况,因为您在forLoop迭代器中使用var关键字,所以其范围将是render函数,并且传递给handleClick的值将始终是迭代器的更新值。 Use let keyword to solve closure issue 使用let关键字解决关闭问题

render(){
    var items = [];
    for (let i = 0; i < 7; i++) {  // let keyword for iterator
      items.push(
        <Item onClick={()=>this.handleClick(i)} />
      );
    }
    return <ul>{items}</ul>;
}

Even with var, you can solve the closure issue using anonymous function 即使使用var,也可以使用匿名函数解决关闭问题

render(){
    var items = [];
    for (var i = 0; i < 7; i++) {
      (function(index){
          items.push(
              <Item onClick={()=>this.handleClick(i)} />
          );
      }.bind(this))(i)
    }
    return <ul>{items}</ul>;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM