问题
Function working while the page load my code as follow
Parent
import React, { Component } from "react";
import ExtnButton from "./Button";
class MovieList extends Component {
handleDelete = index => {
console.log("inside handleDelete:");
};
render() {
return (
<React.Fragment>
<ExtnButton handleDelete={this.handleDelete} index={index} />
</React.Fragment>
);
}
}
export default MovieList;
Child
import React, { Component } from "react";
class Button extends Component {
state = {};
render() {
return (
<button
onClick={this.props.handleDelete(this.props.index)}
className="btn btn-danger"
>
Delete
</button>
);
}
}
export default Button;
But on page loading the function handleDelete invoking without any click event
回答1:
It's because you're calling the method inside the onClick event directly. There are three approaches to bind the events with the parameters:
Using inline arrow function:
onClick={() => this.props.handleDelete(this.props.index)}
Using public class method (as you also have currently), but just need to curry:
handleDelete = index => () => {
console.log("inside handleDelete:");
};
Using bound method:
handleDelete(index) {...}
But for this, you need to bind the this
inside the constructor.
this.handleDelete = this.handleDelete.bind(this)
If you need to pass the event:
(using inline arrow function)
onClick={(e) => this.props.handleDelete(this.props.index, e)}
(using public class method)
handleDelete = index => e => {
console.log(e);
};
Notice that if you use inline arrow function, then you don't need to curry the function. This will be just fine:
handleDelete = index => {...}
Or, without using public class method (ie. bound method):
handleDelete(index) {...}
回答2:
Wrong:
onClick={this.props.handleDelete(this.props.index)}
Correct:
onClick={() => this.props.handleDelete(this.props.index)}
来源:https://stackoverflow.com/questions/52370100/reactjs-function-invoking-on-page-load-before-onclick-event