1.在render中使用bind

  1. class App extends React.Component {
  2. handleClick() {
  3. console.log('this > ', this);
  4. }
  5. render() {
  6. return (
  7. <div onClick={this.handleClick.bind(this)}>test</div>
  8. )
  9. }
  10. }

2.在render中使用箭头函数

  1. class App extends React.Component {
  2. handleClick() {
  3. console.log('this > ', this);
  4. }
  5. render() {
  6. return (
  7. <div onClick={() => this.handleClick}>test</div>
  8. )
  9. }
  10. }

3.在构造函数中使用bind

constructor中预先bind当前组件,可以避免在render操作中重复绑定

  1. class App extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.handleClick = this.handleClick.bind(this);
  5. }
  6. handleClick() {
  7. console.log('this > ', this);
  8. }
  9. render() {
  10. return (
  11. <div onClick={this.handleClick}>test</div>
  12. )
  13. }
  14. }

4.在定义阶段使用箭头函数绑定

  1. class App extends React.Component {
  2. handleClick = () => {
  3. console.log('this > ', this);
  4. }
  5. render() {
  6. return (
  7. <div onClick={this.handleClick}>test</div>
  8. )
  9. }
  10. }

5.区别

上述四种方法的方式,区别主要如下:

  • 编写方面:方式一、方式二写法简单,方式三的编写过于冗杂
  • 性能方面:方式一和方式二在每次组件render的时候都会生成新的方法实例,性能问题欠缺。若该函数作为属性值传给子组件的时候,都会导致额外的渲染。而方式三、方式四只会生成一个方法实例

综合上述,方式四是最优的事件绑定方式