如何访问地图内正确的“this”:ReactJS [重复]

2024-06-24

例如,我有一个具有两种绑定方法的反应组件:

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其中之一是handleRemoveComment. handleSubmit功能有效但是handleRemoveComment没有。运行时,返回错误:

类型错误:无法读取未定义的属性“handleRemoveComment”


问题出在这一行:

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

因为你忘记绑定了renderComment,map回调方法,所以this inside renderComment方法不会引用类上下文。

Use any one这些解决方案,它会起作用。

1-使用此行constructor:

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

2- Pass this与 与map like:

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

3-使用箭头函数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()}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何访问地图内正确的“this”:ReactJS [重复] 的相关文章

随机推荐