hh54188
hh54188

Reputation: 15626

React.js: Confuse about `this` keyword context

I have one parent component and child component, which the parent include the child one. They have the same counter state:

import React from 'react';

class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            counter: 100
        }
    }
    render = () => {
        return (
            <div>
                <h2>{this.state.counter}</h2>
                <button onClick={this.props.clickHandler.bind(this)}>Click</button>
            </div>
        )
    }
}

export default class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            counter: 0
        }
    }
    addCounter = () => {
        this.setState({
            counter: ++this.state.counter
        })
    }
    render = () => {
        return (
            <div>
                <h1>{this.state.counter}</h1>
                <Child clickHandler={this.addCounter} />
            </div>
        )
    }
}

I pass the addCounter handler from parent to the child one, and I think the context of the addCounter could change from parent to child through bind method, then when I click the button, the counter in child would increased instead of the parent counter state.

But the fact is, no matter the clickHandler bind null or this, the function only increase the parent's state counter.

So what's wrong with my thought, why the context doesn't change?

Upvotes: 1

Views: 749

Answers (2)

Nicola Pedretti
Nicola Pedretti

Reputation: 5166

It is because you are using arrow functions. It is one of the purposes of arrow functions to maintain the "this" of the parent. This should explain it.

Change:

addCounter = () => { //your code}

To:

addCounter () {//your code}

Upvotes: 1

Dark Falcon
Dark Falcon

Reputation: 44181

Because you have defined addCounter via the ES6 arrow function syntax, this is already implicitly bound to the parent object. You can bind the function again but this has no effect, as the binding is already in place.

Upvotes: 0

Related Questions