javascript - ReactJS webpack babel : _this2 is undefined when clicking button whose function is passed via a parameter

标签 javascript reactjs webpack babeljs es6-class

毫无疑问,我在这里错过了一些非常明显的东西,但我正在尝试做 lynda 教程“学习 React.js”,它有点不同,因为我使用 ES6 类并通过 webpack 使用 Babel 进行转译。

问题是执行一个函数作为参数从 Board 类传递给 Note 类。

我有一个“Note”类,可以描述为:

remove() {
    this.props.onRemove(this.props.id);
}
//Notes class
render() {
    return (
        <div className="note">
            <p>{this.props.children}</p>
            <span>
                <button onClick={() => this.remove() }>X</button>
            </span>
        </div>
    );
}

其中 onRemove 是一个作为 props 从 Board 传递到 Note 的函数,如下所示:

//Method in Board class. I map through an array and call this function on each element to create notes.
eachNote(note) {
    return (
        <Note key = { note.id } id = { note.id } onRemove = { (id) => this.remove(id) }>
            { note.note }
        </Note>
    )
}

Board 类中的remove() 方法如下所示:

//Remove method in the Board class
remove(id) {
    let notes = this.state.notes.filter(note => note.id !== id);
    this.setState({notes});
} 

当我单击 Note 的 X 按钮时,它会执行 note 类中的本地函数,但不会执行作为属性传递的方法 (onRemove()),而是得到 (Firefox):

TypeError: _this2 is undefined

在 Chrome 中我得到:

Cannot read property 'remove' of undefined

我不明白为什么它找不到该函数,我之前做了一个教程,它正是这样做的,并且能够正常找到该函数。我可能忽略了一些非常简单的事情。

[编辑:额外的主板信息]

//Board's render method
render() {
    return (
        <div className='board'>
            { this.state.notes.map(this.eachNote) }
        </div>
    );
}

在控制台中它输出我期望的内容。

最佳答案

经过一个下午的尝试,我想展示我的解决方案,以防其他人遇到这个问题。

我的渲染方法是通过注释数组进行映射并从每个元素进行创建。问题是我没有将“notes”对象传递给创建 note 元素的函数。所以我通过将渲染方法更改为以下内容来修复它:

render() {
    return (
        <div className='board'>
            { this.state.notes.map((note) => this.eachNote(note)) }
        </div>
    );
}

我不确定,但我认为这是可行的,因为每个 Note 实例都有自己的 this 。如果有人有更好的解释请告诉我。

关于javascript - ReactJS webpack babel : _this2 is undefined when clicking button whose function is passed via a parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47537685/

相关文章:

javascript - jQuery 在 IE7 中不生成 DIV

Javascript:打开和关闭输入标签仅适用于表单中的最后一个标签

javascript - 多重提交按钮和回车键

reactjs - react 路由器仅渲染第一条路线

javascript - 如何将隐藏属性 "draggable"传递给我的组件?

css - 基础网格系统不生效

css - 使用通过 NPM/Webpack 安装的 basscss

javascript - Twitter typeahead 0.1 w/bloodhound - 无法使用 URL 进行预取

javascript - react : Why is `this.props.children` undefined?

reactjs - WebPack 与 React 未捕获引用错误