admin管理员组文章数量:1328013
In this tutorial he uses an onClick function with bind.
<Card onClick={that.deletePerson.bind(null, person)} name={person.name}></Card>
When I remove the bind like this
<Card onClick={that.deletePerson(person)} name={person.name}></Card>
I get an error
Uncaught Error: Invariant Violation: setState(...): Cannot update during an existing state transition (such as within
render
). Render methods should be a pure function of props and state.
I know what bind
does, but why is it needed here? Is the onClick
not calling the function directly?
(code is in this JSbin: )
In this tutorial he uses an onClick function with bind.
<Card onClick={that.deletePerson.bind(null, person)} name={person.name}></Card>
When I remove the bind like this
<Card onClick={that.deletePerson(person)} name={person.name}></Card>
I get an error
Uncaught Error: Invariant Violation: setState(...): Cannot update during an existing state transition (such as within
render
). Render methods should be a pure function of props and state.
I know what bind
does, but why is it needed here? Is the onClick
not calling the function directly?
(code is in this JSbin: https://jsbin./gutiwu/1/edit)
Share Improve this question asked Apr 7, 2015 at 15:31 ilyoilyo 36.4k46 gold badges108 silver badges161 bronze badges 01 Answer
Reset to default 7He's using the bind
so that the deletePerson
method gets the correct person
argument.
Because the Card
ponent doesn't get a full Person
object, this allows him to identify which person's card was actually clicked.
In your example, where you removed the bind onClick={that.deletePerson(person)}
is actually evaluating the function that.deletePerson(person)
and setting that as onClick. The deletePerson
method changes the Component's state, which is what the error message is saying. (You can't change state during a render).
A better solution might be to pass the id into Card, and pass it back up to the app ponent on a delete click.
var Card = React.createClass({
handleClick: function() {
this.props.onClick(this.props.id)
}
render: function () {
return (
<div>
<h2>{this.props.name}</h2>
<img src={this.props.avatar} alt=""/>
<div></div>
<button onClick={this.handleClick}>Delete Me</button>
</div>
)
}
})
var App = React.createClass({
deletePerson: function (id) {
//Delete person using id
},
render: function () {
var that = this;
return (
<div>
{this.state.people.map(function (person) {
return (
<Card onClick={that.deletePerson} name={person.name} avatar={person.avatar} id={person.id}></Card>
)
}, this)}
</div>
)
}
})
本文标签:
版权声明:本文标题:javascript - In React, why do I have to bind an onClick function rather then calling it? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742245474a2439201.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论