React 缺少 onClick?
React missing an onClick?
我在组件中有以下代码:
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>
)
}
但是,我发现 createShare
中锚点上的 onClick 似乎没有触发,就像它没有绑定一样。控制台中没有错误或任何内容。
我假设 React 设置事件绑定的方式有些奇怪,或者某种上下文问题。我该如何解决?
In createShare
this
将绑定到 window,因为它在函数内部。
您可以将 createShare
更改为组件上的方法,React 将 autobind it to the component, or bind it to what you expect with Function.prototype.bind
另一个不错的解决方案是 ES6 arrow functions,它将 this
绑定到它们定义的范围,但这需要一些设置
我在组件中有以下代码:
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>
)
}
但是,我发现 createShare
中锚点上的 onClick 似乎没有触发,就像它没有绑定一样。控制台中没有错误或任何内容。
我假设 React 设置事件绑定的方式有些奇怪,或者某种上下文问题。我该如何解决?
In createShare
this
将绑定到 window,因为它在函数内部。
您可以将 createShare
更改为组件上的方法,React 将 autobind it to the component, or bind it to what you expect with Function.prototype.bind
另一个不错的解决方案是 ES6 arrow functions,它将 this
绑定到它们定义的范围,但这需要一些设置