小编典典

如何在地图内访问正确的“ this”:ReactJS

reactjs

例如,我有一个带有两种绑定方法的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">
                       &times;
                  </button>
            </div>
        )
    }

    render() {
        return(
            <div className="comments">

                {this.props.postComments.map(this.renderComment)}

                .....
            </div>
        )
    }
}

export default Comments;

在上面的代码中,我有两种绑定方法:一种是handleSubmit和一种是handleRemoveCommenthandleSubmit功能有效,但handleRemoveComment无效。运行时,它返回错误:

TypeError:无法读取未定义的属性“ handleRemoveComment”


阅读 247

收藏
2020-07-22

共1个答案

小编典典

问题在于这条线:

{this.props.postComments.map( this.renderComment )}

因为您忘记了绑定renderComment,映射回调方法,所以thisinside renderComment方法将不会引用类上下文。

使用这些解决方案中的 任何一种 ,它将起作用。

1-constructor以下位置使用此行:

this.renderComment = this.renderComment.bind(this) ;

2- 通过thismap喜欢:

{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">
                        &times;
                    </button>
                </p>
            </div>
        )
    })
}

并从中调用此方法render,在这种情况下,renderComment不需要绑定:

{this.renderComment()}
2020-07-22