Thursday, January 30, 2020

[React][Resolved] Element onClick event called when page load


What I expect is pop up an alert box after clicked the "Change: button.
But right now the alertbox show when page load

Source code
class Blog extends React.Component {
   constructor(props) {
    super(props);
    this.state = {
 posts: "123",
 comments: "abc"
    };
  }
  changeText(){
    alert("Click change button");
  }
  render() {
    return (
      <div>
        <p>{this.state.posts}</p>
        <p>{this.state.comments}</p>
        <button onClick={this.changeText()}>Change</button>
      </div>
    );
  }
}
Since I used the wrong syntax to call function, remove the brakets after changeText() works .
<button onClick={this.changeText}>Change</button>

Reference:
https://reactjs.org/docs/handling-events.html

No comments :

Post a Comment