javascript - 绑定(bind)函数作为属性传递 React

标签 javascript html css reactjs

我试图传递一个绑定(bind)函数(参数)(有一个 setState())作为属性,但我遇到了这个错误,我实际上不确定如何传递这种函数。

Cannot read property 'upadateComment' of undefined

这是我在 index.js 文件中的类片段,(具有函数的类)

removeComment = (i) => {
    console.log('removing comment: ' + i);
    var arr = this.state.comments;
    arr.splice(i, 1);
    this.setState({comments: arr});
}

upadateComment = (newText , i) => {
    console.log('updating comment: ' + i);
    var arr = this.state.comments;
    arr[i] = newText;
    this.setState({comments: arr});
}


eachComment(text, i) {
    return (
        <Comment                            
        key={i} index={i} updateCommentText={this.upadateComment}//here is the problem
        removeCommentText={this.removeComment}> //and here 
        {text}
        </Comment>
    );
}

render() {
    return (
        <div>
            {this.state.comments.map(this.eachComment)}
        </div>
    );
}

这是调用它们的地方(Comment.js 文件)

edit = () => {
    this.setState({editing: true});
}

remove = () => {
    this.props.removeCommentText(this.props.index);
    console.log('removing');
}

save = () => {
    this.props.updateCommentText(this.refs.newText.value , this.props.index);
    console.log('new Text: ');
    this.setState({editing: false});
}

最佳答案

由于 eachComment 是一个函数声明,它引用了错误的 this 上下文。我建议您将其更改为 arrow function

eachComment = (text, i) => {
    return (
        <Comment                            
        key={i} index={i} updateCommentText={this.upadateComment}
        removeCommentText={this.removeComment}>
        {text}
        </Comment>
    );
}

关于javascript - 绑定(bind)函数作为属性传递 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47490501/

相关文章:

php - MYSQL之谜。传递给函数的值不正确

javascript - 如果没有牙套就让进来

jquery - CSS 下拉菜单、z-index、iframe 有问题吗?

html - 填充字段集,IE 有问题

javascript - 单击滚动按钮时不想将 anchor href 添加到 url

html - 如何在 Android 手机上设置选择元素的样式?

javascript - 如果没有值,则更改选择框的宽度

html - 无法调整表格大小以适应 div 内容

javascript - 缩放背景图像时,它开始在 Chrome 中闪烁

javascript - 火狐插件 : What is the best way to insert a large chunk of HTML?