0

does this keyword here refer to the class instance or to the props object

onClick: this.handleClick

In the following code example, we have a React class Component mental model. Inside the render function, we are returning a plain JS object which has a functional prop called 'onClick'.

class Component {
  constructor() {
    this.state = 10;
    this.setState = function() {
      console.log('state');
    };
  }

  handleClick() {
    this.setState();
  }

  render() {
    // return a child component.
    return {
      type: 'button',
      props: {
        // pass functional props
        onClick: this.handleClick,
        children: 'Click Me'
      }
    };
  }
}

// 1. creating a component instance
const componentInstance = new Component();

// 2. calling a render method on the instance
// ( In reality, React does the same thing for your class components)
const element = componentInstance.render();

// 3. calling the onClick function, which was passed as a  prop,
// will throw a 'TypeError: this.setState is not a function'.
element.props.onClick();
Alvah_Franey
  • 121
  • 2
  • 6
  • 1
    In this case, the function is from the class definition but the `this` context is from `props` object. Thus `this.setState` does not exist. Consider assigning the `this` context manually: `onClick: this.handleClick.bind(this)` – Hao Wu Oct 18 '22 at 06:09

0 Answers0