How to write the event binding of React notes

Event binding of class components

  1. <button onClick={() => this.addN()}>n+1</button>

    This way of writing is normal, just pass a function to onClick, pay attention to case.

  2. <button onClick={this.addN}>n+1</button>

    This way of writing is wrong, it will make this in this.addN become window,

    Let's change the correct way of writing

    1. <button onClick={this.addN.bind(this)}>n+1</button>

      This is enough to write, so that this will be bound to the current this instead of becoming a window.

    2. Give the arrow function a name,

    this._addN = () => this.addN()

    then

    <button onClick={this._addN}>n+1</button>

    That's it.

    1. Directly change addN to an arrow function
    constructor() {
        this.addN = () => this.setState({n: this.state.n + 1})
    }
    render() {
        return <button onClick={this.addN}>n+1</button>
    }
    
    1. Final wording

      Write directly in the class component

      addN = () => this.setState({n: this.state.n + 1})

      render() {
          return <button onClick={this.addN}>n+1</button>
      }
      

The difference between writing

Writing one:

class Son extends React.Component {
	addN = () => this.setState({n: this.state.n + 1}) // 这种写法等价于下面的写法,这里少写了一个this
  constructor() {
  	this.addN = () => this.setState({n: this.state.n + 1}) // 与上面的写法相等
  }
}

Writing two:

class Son extends React.Component {
	//与下面的写法相同
	addN() {
  	this.setState({n: this.state.n + 1})
  }
  //与上面的写法相同
  addN: function() {
  	this.setState({n: this.state.n + 1})
  }
}

The difference between writing method one and writing method two is that the method one is hung on the object, and the method two is hung on the prototype. Let's verify it below:

Writing method 1: When writing the method directly with an arrow function, when an object comes out, the method is directly hung on the object, as shown in the figure below:

The second way of writing is to write the method directly in the class. When the new object comes out, the method is directly hung on the prototype chain. The following picture witnesses:

The word this in the first method is immutable and always points to the created object. The this in the second method is determined by the caller and may become other objects.

Because the function arrow does not accept this, which is the above statement, only belongs to the object that created it.

Guess you like

Origin blog.csdn.net/cainiao1412/article/details/108375118