0

I'm learning React and trying to understand the difficulty of "this". I know that "this" in method will refer to "button" instead of instance of the class without binding "this". So I plan to verify this conclusion, but when I click the button, the browser console displays “undefined” instead of button element. I'm quite confused.

I know that I should bind "this" manually and shouldn't use class components. I just want to test it and during my learning process, I encountered a problem that I don't know the reason.

import React from "react";

export class HerCom extends React.Component {
  constructor(props) {
    super(props);
    this.state = { happy: 100 };
  }

  handleClick() {
    const newHappy = this.state.happy === 100 ? 0 : 100;
    this.setState({ happy: newHappy });
  }

  testThis() {
    console.log(this);
  }

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

I hope someone can tell me why I didn't get the expected result.

scott-p
  • 3
  • 2
  • 3
    In React class components, you need to bind your functions to `this` manually. The documentation goes in detail about it here: https://reactjs.org/docs/handling-events.html (search for "class methods are not bound"). This is not React specific by the way. – nbokmans Feb 28 '23 at 13:17
  • 1
    Also... you should really avoid using class components for React. It's marked for deprecation. Use functional components instead. – Terry Feb 28 '23 at 13:17
  • I know that I should bind "this" manually and shouldn't use class components. I just want to test it and during my learning process, I encountered a problem that I don't know the reason. – scott-p Feb 28 '23 at 13:37

0 Answers0