【问题标题】:Reactjs function binding on event handler事件处理程序上的 Reactjs 函数绑定
【发布时间】:2019-05-27 13:57:33
【问题描述】:

我试图理解为什么我们必须将对象 null 绑定到函数

add(text) {
    this.setState(prevState=> ({
        notes: [
            ...prevState.notes,
            {
                id: this.nextId(),
                note: text
            }
        ]
    }))
}

render() {
    return (
        <div className="board">
            {this.state.notes.map(this.eachNote)}
            <button onClick={this.add.bind(null, "New Note")}
                id="add">Add note</button>
        </div>
    )
}

为什么我们不能只做this.add("New Note")?

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

onClick={this.add("New Note")} 将立即运行add() 方法,然后将结果设置为onClick。 add() 的结果是未定义的,因为它不返回任何内容。所以我们基本上会做onClick={undefined}。

为了解决这个问题,我们可以使用匿名函数:onClick={() =&gt; this.add("New Note")}
这一次,当按钮被点击时,程序正确地调用了this.add("New Note")。

或者我们可以利用bind() 允许我们声明this 上下文和我们想要传递的参数这一事实,并简单地使用onClick={this.add.bind(this, "New Note")}(使用this 作为第一个参数绑定实例作为上下文,就像第二段中的箭头函数)

【讨论】:

    猜你喜欢
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多