You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.
classLoggingButtonextendsReact.Component{// This syntax ensures `this` is bound within handleClick.// Warning: this is *experimental* syntax.handleClick=()=>{console.log('this is:',this);}render(){return(<buttononClick={this.handleClick}>
Click me
</button>);}}
classLoggingButtonextendsReact.Component{handleClick(){console.log('this is:',this);}render(){// This syntax ensures `this` is bound within handleClickreturn(<buttononClick={(e)=>this.handleClick(e)}>
Click me
</button>);}}
The text was updated successfully, but these errors were encountered:
其实看官方文档的时候,文档也会这么建议:
由于js特殊的机制原因,this往往是在运行时决定的。不同的调用环境决定了不同的this指向。render中传进去的事件往往作为回调。所以回调函数被触发的时候this指向的是window对象,并不是指向这个组件。bind是为了重新将this绑定到组件上。
具体可读SyntheticEvent
所以也就有文档推荐的两种做法:
The text was updated successfully, but these errors were encountered: