以下代码中的this.tick.bind(this)语句中bind做了什么:
export class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
tick() {
this.setState({count: this.state.count + 1});
}
render() {
return (
<div onClick={this.tick.bind(this)}>
Clicks: {this.state.count}
</div>
);
}
}
代码取自React网站。
最佳答案
.bind()
将其用于创建的函数的 this
设置为传入的任何参数。Docs here .
在本例中,它将 tick()
函数的 this
设置为 render()
函数的上下文。
您会这样做,因为当函数用作 DOM 事件处理程序时,this
被设置为调度 DOM 事件的元素。您想要保证 this
是您所期望的,因为它在 tick()
关于reactjs - 在这个 react 示例中,bind 做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32124213/