SoFunction
Updated on 2025-04-07

Implementation of event binding this pointing to three methods in React

1. Arrow function

1. Use the characteristics of the arrow function itself not binding this;

This in the () method is a component instance, and you can get setState();

class App extends {
    state ={
        count: 0
    }
    // Event handler    onIncrement() {
        ('This in event handler function:',this)
        ({
            count:+1
        })
    }
    // Rendering    render() {
        return (
            <div>
                <h1> {}</h1>
              // This in the arrow function points to the external environment, here is: render() method                <button onClick={()=>()}>+1</button>
                {/* <button onClick={()}>+1</button> */}
            </div>
        )
    }
}

()

1. Use the bind method in ES5 to bind this in the event handler to the component instance.

class App extends {
    constructor() {
        super()
        // data         ={
            count: 0
        }
        // The first method.bind changes this pointing, returns a function, and does not execute the function         = (this)
    }
     // Event handler     onIncrement() {
         ('This in event handler function:',this)
         ({
             count:+1
         })
     }
    // Rendering    render() {
        return (
            <div>
                <h1> {}</h1>
                <button onClick={}>+1</button>
                {/* <button onClick={()}>+1</button> */}
            </div>
        )
    }
}

Example method

1. Use the class instance method in the form of arrow function

2. This syntax is experimental syntax, but it can be used directly due to the existence of babel.

class App extends {
    constructor() {
        super()
        // data         ={
            count: 0
        }
    }
      // Event handler      onIncrement=()=> {
        ('This in event handler function:',this)
        ({
            count:+1
        })
    }
    // Rendering    render() {
        return (
            <div>
                <h1> {}</h1>
                <button onClick={}>+1</button>
                {/* <button onClick={()}>+1</button> */}
            </div>
        )
    }
}

This is the article about the implementation of three methods of event binding this pointing to React. For more related React event binding this pointing to content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!