This problem in react component method

1 clipboard.png

2
clipboard.png

as shown in the two figures above: in the react component, it is known that all other environments are the same, except that there is an extra layer of arrow function in figure 1. Ask: why is it that in the scroll method of this component, this is taken in the form of figure 1, while this in the form of figure 2 is undefined??

Feb.27,2021

1. First of all, the this of the arrow function is statically bound
2. To understand that onScroll registers event callbacks, that is, it should be followed by a function. When the croll event is triggered, the function after the equal sign is executed. The second way of writing is that your scroll () is executed on render, not when the event is triggered, and the this in it is not undefined

.



clipboard.png


this problem starts with class .
when defining React components, extends React.Component does not inherit this . So your second graph is this is undefined .
while the arrow function in ES6 is bound to this by default when it is defined.
there are generally two ways to use this .

  • use the arrow function directly
  • binds in constructor.
class {
    constructor() {
        super(...arguments);
        this.myFunction = this.myFunction.bind(this);
    }
    
    render() {
        return(
            <div onClick={this.myFunction}></div>
        )
    }
    
    myFunction() {
        //
    }
}
Menu