简体   繁体   中英

Function in my class is always getting called on page load, when I only want it called onClick

I have a function that I want to call only onClick. However it's getting called right when the page loads, and then the onClick doesn't call it again afterwards.

handleIncrement() is what I'm trying to call, that's being called on load, and the button in render is where I'm trying to have it called onClick.

class Counter extends Component {
  state = {
    count: 0
  };

  handleIncrement() {
    console.log("Increment Clicked", this.state.count);
  }

  render() {
    return (
      <div>
        <span style={{ fontSize: 20 }} className={this.getBadgeClasses()}>
          {this.formatCount()}
        </span>
        <button
          onClick={this.handleIncrement()}
          style={{ fontSize: 25 }}
          className="btn btn-secondary btn-sm 30"
        >
          Increment
        </button>
      </div>
    );
  }

  getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

  formatCount() {
    const { count } = this.state;
    return count === 0 ? "Zero" : count;
  }
}

将其更改为onClick={() => this.handleIncrement()}

onClick={this.handleIncrememt}

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