例如,我有一个带有两种绑定方法的react组件:
import React from 'react'; class Comments extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); this.handleRemoveComment = this.handleRemoveComment.bind(this); } handleSubmit(e) { ..... } handleRemoveComment(e) { //this.props.removeComment(null, this.props.params, i); } renderComment(comment, i) { return( <div className="comment" key={i}> ..... <button onClick={this.handleRemoveComment} className="remove-comment"> × </button> </div> ) } render() { return( <div className="comments"> {this.props.postComments.map(this.renderComment)} ..... </div> ) } } export default Comments;
在上面的代码中,我有两种绑定方法:一种是handleSubmit和一种是handleRemoveComment。handleSubmit功能有效,但handleRemoveComment无效。运行时,它返回错误:
handleSubmit
handleRemoveComment
TypeError:无法读取未定义的属性“ handleRemoveComment”
问题在于这条线:
{this.props.postComments.map( this.renderComment )}
因为您忘记了绑定renderComment,映射回调方法,所以thisinside renderComment方法将不会引用类上下文。
renderComment
this
使用这些解决方案中的 任何一种 ,它将起作用。
1- 在constructor以下位置使用此行:
constructor
this.renderComment = this.renderComment.bind(this) ;
2- 通过this与map喜欢:
map
{this.props.postComments.map(this.renderComment, this)}
3- 将Arrow函数与renderComment方法配合使用,如下所示:
renderComment = (comment, i) => { .....
或在renderComment函数内部使用地图(我以前更喜欢这种方式),如下所示:
renderComment() { return this.props.postComments.map((comment, i) => { return( <div className="comment" key={i}> <p> <strong>{comment.user}</strong> {comment.text} <button onClick={this.handleRemoveComment} className="remove-comment"> × </button> </p> </div> ) }) }
并从中调用此方法render,在这种情况下,renderComment不需要绑定:
render
{this.renderComment()}