React missing onClick?
I have the following code in a component:
deleteShare: function(e) {
console.dir(e);
},
render: function() {
createShare = function(share) {
return (
<span key={share} className='share'>
{share}
<a href="#" onClick={this.deleteShare}>x</a>
</span>
)
}
return (
<div>
<input type='hidden' name='shares' value={this.state.shares.join(',')} />
<div className='ticket_shares'>
{this.state.shares.map(createShare)}
<input type='text' id='new_share' placeholder='Add an email' onKeyDown={this.addShare}/>
</div>
</div>
)
}
However, I found that onClick on anchor in createShare
doesn't seem to fire, as if it is optional. There is no error or anything in the console.
I'm guessing something funky is going on with the way React sets up event bindings or some kind of context issue. How can I solve this?
source to share
B createShare
this
will be bound to the window as it is inside the function.
You can change createShare
to a method on the component and React will automatically bind it to the component or bind it to whatever you expect with Function.prototype.bind
Another nice solution is the ES6 arrow functions that bind this
to the scope they are defined in, but that will take a bit of customization
source to share