this.function = this.function.bind(this)在以下上下文中做了什么? ReactJS

时间:2017-06-04 02:40:14

标签: reactjs

我正在关注udemy的教程系列,教师还没有真正解释以下代码行:

this.getrandomnum = this.getrandomnum.bind(this);

所以我对它的作用感到有些困惑,希望得到一些帮助。我的代码可以使用或不使用上面的代码。

以下是完整代码:

class App extends Component {
  render() {
    return (
      <div className="App">
      <h1> Hello</h1>
      <Body />
      </div>
    );
  }
}

class Body extends Component{
  constructor(props){
    super(props);
    this.state = {};
    this.getRandomNumber = this.getRandomNumber.bind(this);
  }
  getRandomNumber(){
    console.log('some random number')
  }
  render(){
    return (
      <button onClick={this.getRandomNumber}>Random Number</button>
      )
  }
}

1 个答案:

答案 0 :(得分:1)

当它被调用时,它会将this绑定到类中的函数。重要的是在this被调用时保留其背景。通常,这是在回调上完成的,例如onClick组件中的Body处理程序。

您的代码仍然有效,因为您没有引用任何类型的上下文(window.console函数除外,在这种情况下是this)。如果你没有在构造函数中绑定this并且有这个:

<button onClick={this.getRandomNumber}>Random Number</button>

getRandomNumber

getRandomNumber(e){
    console.log(e)
}

它将返回eundefined的错误,因为此函数的上下文绑定到window对象。在这种情况下,e不存在。

详细了解:handling events in the React docsbind