1.在render中使用bind
class App extends React.Component {
handleClick() {
console.log('this > ', this);
}
render() {
return (
<div onClick={this.handleClick.bind(this)}>test</div>
)
}
}
2.在render中使用箭头函数
class App extends React.Component {
handleClick() {
console.log('this > ', this);
}
render() {
return (
<div onClick={() => this.handleClick}>test</div>
)
}
}
3.在构造函数中使用bind
在
constructor
中预先bind
当前组件,可以避免在render
操作中重复绑定
class App extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('this > ', this);
}
render() {
return (
<div onClick={this.handleClick}>test</div>
)
}
}
4.在定义阶段使用箭头函数绑定
class App extends React.Component {
handleClick = () => {
console.log('this > ', this);
}
render() {
return (
<div onClick={this.handleClick}>test</div>
)
}
}
5.区别
上述四种方法的方式,区别主要如下:
- 编写方面:方式一、方式二写法简单,方式三的编写过于冗杂
- 性能方面:方式一和方式二在每次组件render的时候都会生成新的方法实例,性能问题欠缺。若该函数作为属性值传给子组件的时候,都会导致额外的渲染。而方式三、方式四只会生成一个方法实例
综合上述,方式四是最优的事件绑定方式