Why did Reate change the directivity of this

Simply put, because callbacks in Reate use this very often, the this reference must be the one we know

instructions

This article is just personal opinion, is used for their own summary of some knowledge points, there is a need for small partners can learn from

Methods a

1. Higher order functions (Currization)🚀

Higher-order functions: Use this to call handleClick directly and return the arrow function.

🧐 Corrification: through the function call to continue to return the form of the function, the realization of multiple received parameters finally unified processing of the function encoding form.

Export default class user extends Component {state = {cound:0} // This extends Component {state = {cound:0} console.log(this); } } render() { return ( <button onClick={this.addEvent()}></button> ) } }Copy the code

Method 2 🚊

2. Wrap a layer of arrow functions.

This in the arrow function points to the “outside”, the Render function, and this in the Render function is the component instance.

export default class user extends Component {
  state = {
    cound:0
  }
  addEvent() {
      console.log(this);
  }
  render() {
    return (
      <button onClick={() => this.addEvent()}></button>
    )
  }
}

Copy the code

Methods three ✈

3. Use the bind

export default class user extends Component {
  state = {
    cound:0
  }
  addEvent() {
      console.log(this);
  }
  render() {
    return (
      <button onClick={this.addEvent.bind(this)}></button>
    )
  }
}
Copy the code

Methods four 🛩

4. Use the assignment statementThe instanceAdd an arrow function above.

export default class user extends Component {
  state = {
    cound:0
  }
  addEvent = () => {
      console.log(this);
  }
  render() {
    return (
      <button onClick={this.addEvent.bind(this)}></button>
    )
  }
}
Copy the code

Methods five 🚅

5. Create an instance method in the constructor, sharing the same body as the prototype method.

class App extends React.Component {
  constructor() {
      super()
      this.state = {
          count: 0,
      }
      this.addClick = this.addClick.bind(this)
  }
  addClick() {
      console.log(this)
  }
  render() {
      return (
          <div>
              <button onClick={this.addClick}>+1</button>
          </div>
      )
  }
}
Copy the code