简体   繁体   中英

Reactjs function binding on event handler

I'm trying to understand why we have to bind an object null to the function

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>
    )
}

Why can't we just do this.add("New Note") ?

onClick={this.add("New Note")} would immediately run the add() method, then set the result as onClick . The result of add() is undefined, because it doesn't return anything. So we'd essentially do onClick={undefined} .

So to fix that, we can use an anonymous function: onClick={() => this.add("New Note")}
This time, the program properly calls this.add("New Note") when the button is clicked.

Or we can just take advantage of the fact that bind() allows us to state the this context and the arguments we want to pass, and simply use onClick={this.add.bind(this, "New Note")} (using this as first argument binds the instance as context, just like the arrow function in the 2nd paragraph)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM