简体   繁体   中英

onClick not firing click handler

My click handler doesn't fire:

submitForm(UserDetails) {
    axios
        .post('http://localhost:3001/api/users', UserDetails)
        .then(function(response) {
            console.log(response);
        })
        .catch(function(error) {
            console.log(error);
        });
} 

ON my button:

<button
            className="btn btn-primary"
            onClick={this.submitForm(this.props.UserDetails)}>
            Upload
        </button>

I have bound it to this, in my constructor:

constructor() {
    super();
    this.submitForm = this.submitForm.bind(this);
}

Any ideas?

In the onClick hook you're invoking the function instead of passing a reference of the function

<button
  className="btn btn-primary"
  onClick={this.submitForm(this.props.UserDetails)}>
  Upload
</button>

remove the bind from the constructor

this.submitForm = this.submitForm.bind(this);

and pass a proper function to the onClick

<button
  className="btn btn-primary"
  onClick={(e) => this.submitForm(this.props.UserDetails)}>
  Upload
</button>

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