你好,我是全栈网站开发的新手,我想了解一下全栈网站开发的概念。"将事件处理程序绑定到类实例",在React中
class Foo extends React.Component{
constructor( props ){
super( props );
this.handleClick = this.handleClick.bind(this); // <- why?
}
handleClick(event){
// your event handling logic
}
render(){
return (
<button type="button"
onClick={this.handleClick}>
Click Me
</button>
);
}
}
ReactDOM.render(
<Foo />,
document.getElementById("app")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
React docs https:/reactjs.orgdocshandling-events.html。
在JSF回调中,你要注意这个意思。在JavaScript中,类方法默认是不绑定的。如果你忘记绑定this.handleClick并将其传递给onClick,那么当函数被实际调用时,这将是未定义的。
这不是React特有的行为,这是JavaScript中函数工作方式的一部分。一般来说,如果你引用一个后面没有()的方法,例如
onClick={this.handleClick}
,你应该绑定该方法。
class Foo extends React.Component{
constructor( props ){
super( props );
}
handleClick(event){
console.log(this); // 'this' is undefined
}
render(){
return (
<button type="button" onClick={this.handleClick}>
Click Me
</button>
);
}
}
ReactDOM.render(
<Foo />,
document.getElementById("app")
);
为了解决这个问题,你可以绑定 this
到类构造函数上的函数
constructor( props ){
super( props );
this.handleClick = this.handleClick.bind(this);
}
公共类字段语法(箭头函数)
class Foo extends React.Component{
handleClick = () => {
console.log(this);
}
render(){
return (
<button type="button" onClick={this.handleClick}>
Click Me
</button>
);
}
}