版权声明:转载请注明作者(独孤尚良dugushangliang)出处: https://blog.youkuaiyun.com/dugushangliang/article/details/90580582
参阅https://www.runoob.com/react/react-event-handle.html
这里的属性初始化器,指的是,handleClick在类中是一个属性,这个属性指的是一个函数。
(本处是个人猜测,未找到可靠资料证实,若有发现或异议请提出)
//handleClick使用属性初始化器语法
class LoggingButton extends React.Component {
// 这个语法确保了 `this` 绑定在 handleClick 中
// 这里只是一个测试
handleClick = () => {
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
这里的绑定,值得是,在render的jsx中,<button>的onClick会调用handleClick方法,但函数/方法在JavaScript是一等公民,所以直接调用,这个this在严格模式下是无所指的,在不严格的情况下是windows,并不是我们创建的这个类的实例。那怎么让这个函数被这个实例所用呢?用bind绑定。注意:这只是绑定,并没有执行这个函数。
//handleClick使用bind绑定函数
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 这边绑定是必要的,这样 `this` 才能在回调函数中使用
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('example')
);
下面的这个箭头函数,指的是,每次点击这个button后,根据onClick,会生成一个箭头函数,这个箭头函数返回 this.handleClick(e),箭头函数的this指的是当前的this(this这个在JavaScript是玄之又玄,不好参悟的,需要多次揣摩其精髓……)。
//handleClick使用箭头函数
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
// 这个语法确保了 `this` 绑定在 handleClick 中
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}
}
上面三种,都可以实现button的点击触发效果,但是箭头函数因为每次调用都要重新生成一个函数,开销较大,而前两者是对同一个函数的反复调用。所以在选择上,各位酌情处置。
独孤尚良dugushangliang——著