我有一个onDeleteClick
函数,当我尝试单击该函数并发出响应时,它给我一个错误,而不是一个函数,并且表明该错误来自此代码
我将单引号更改为反引号,但仍然得到相同的结果
class Contact extends Component {
state = {
showContactInfo: false
};
onDeleteClick = (id, dispatch) => {
dispatch({ type: "DELETE_CONTACT", payload: id });
};
render() {
const { name, id, email, phone } = this.props.contact;
const { showContactInfo } = this.state;
return (
<Consumer>
{value => {
const { dispatch } = value;
return (
<div className="card card-body mb-3">
<h4>
{name}
<i
onClick={() =>
this.setState({
showContactInfo: !this.state.showContactInfo
})
}
className="fas fa-sort-down"
style={{ cursor: "pointer", color: "indigo" }}
/>
<i
className="fas fa-times"
style={{ cursor: "pointer", float: "right", color: "blue" }}
onClick={this.onDeleteClick.bind(this, id, dispatch)}
/>
</h4>
{showContactInfo ? (
<ul className="list-group">
<li className="list-group-item">Email: {email}</li>
<li className="list-group-item">Phone: {phone}</li>
</ul>
) : null}
</div>
);
}}
</Consumer>
);
}
}
Contact.propTypes = {
contact: PropTypes.object.isRequired
};
export default Contact;
我希望onDelete
函数能够从列表中删除。
答案 0 :(得分:0)
在类实例中使用箭头功能时,不必绑定onDeleteClick
。
此外,您调用onDeleteClick
而不是将其分配为回调。
// On given params, return a function
onDeleteClick = (id, dispatch) => () => {
dispatch({ type: "DELETE_CONTACT", payload: id });
};
class Contact extends Component {
...
// v Assign as a callback
onDeleteClick = (id, dispatch) => () => {
dispatch({ type: "DELETE_CONTACT", payload: id });
};
render() {
const { id , ... } = this.props.contact;
return (
<Consumer>
{value => {
const { dispatch } = value;
return (
<div>
<h4>
...
<i
// v No bind needed
onClick={this.onDeleteClick(id, dispatch)}
/>
</h4>
</div>
);
}}
</Consumer>
);
}
}