简体   繁体   中英

in react inside a Component , why we require to use “this.” to give reference to a function

class First extends React.Component{
    handleClick(){
        alert('handle click');
    } 

    render(){
        return <div>
            <button onClick={this.handleClick}>click</button>
        </div>;
    }
 }

in above example why we need to use this.handleClick instead of just handleclick

when this is not used

'handleClick' is not defined no-undef

an indepth explanation is appreciated

This isn't a React thing. It's a JavaScript thing.

Without this. , handleClick is an identifier reference, and that means you have to have an in-scope declared variable with the name handleClick . You don't have that. You have a property on the component instance called handleClick , but that's not in scope anywhere.

It's the same reason you need this here:

 class Example { constructor(value) { this.value = value; } showValue() { console.log(this.value); // <== Works } brokenShowValue() { console.log(value); // <== ReferenceError, `value` is not defined } } const e = new Example(42); e.showValue(); e.brokenShowValue(); 

There are languages which allow this. to be implicit (such as Java and C#), but JavaScript does not.


Side note: If at some point you use this in handleClick (you don't currently), be sure to read this question's answers . You'll need to do something to ensure that the correct this is available within the call (your code doesn't do that at the moment).

Because in JavaScript class properties and methods are not available directly by their name:

class Foo {
    bar() {}
    test() {
        bar(); // Error: undefined function
    }
}

When you call bar() in the example above, JavaScript tries to find the function called bar in the global namespace.

You need to type this. explicitly to access a current object property or method:

class Foo {
    bar() {}
    test() {
        this.bar(); // OK
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM