首页 > 解决方案 > 在 React 中将函数传递给组件的新属性

问题描述

嗨,我正在尝试在 React 中尝试几个代码片段。以下代码生成“无法读取未定义的属性 'removeComment'”类型错误。我已尝试使用不同的技术将函数绑定到反应文档https://reactjs.org/docs/faq-functions.html中描述的类,但问题仍然存在。以下是我的代码:

class Board extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            comments: ["item1", "item2", "item3"]
        }
        this.removeComment = this.removeComment.bind(this);
        this.updateComment = this.updateComment.bind(this);
    }

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

    updateComment = (newText, i) => {
        var arr = this.state.comments;
        arr[i] = newText
        this.setState({ comments: arr })

    }

    eachComment(text, i) {
        return (<Comment key={i} index={i}
            deleteComment={this.removeComment.bind(this)}
            updateCommentText={this.updateComment.bind(this)}>{text}</Comment>)
    }

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

标签: javascriptreactjsjsx

解决方案


推荐阅读