React 渲染一个组件会触发 onClick 事件
React rendering a component triggers the onClick event?
var CustomerTable = React.createClass({
addEmailButton: function(customerId) {
console.log(customerId);
return (
<button onClick={console.log("clicked", customerId)}>X</button>
)
},
render: function() {
var self = this;
return (
<div>
<table>
<thead>
<tr>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
this.state.customers.map(function(customer, i) {
return (
<tr key={i}>
<td>{self.addEmailButton(customer['id'])}</td>
</tr>
)
})
}
</tbody>
</table>
</div>
)
}
});
呈现此组件时,无需单击任何按钮即可执行控制台.log调用。
我只想在单击按钮时调用一个方法,没有什么真正复杂的。
为什么?
看起来您正在尝试使用 addEmailButton
作为customerId
的闭包,但这无济于事,因为需要 customerId
参数的是处理程序,而不是按钮的呈现。
您所需要的只是使用 customerId
参数bind
click 事件:
var CustomerTable = React.createClass({
handleClick: function(customerId, event) {
console.log("clicked", customerId);
},
render: function() {
var self = this;
return (
<...>
{
this.state.customers.map(function(customer, i) {
return (
<tr key={i}>
<td>
<button onClick={self.handleClick.bind(self, customer['id'])}>X</button>
</td>
</tr>
)
})
}
<...>
)
}
});
或者,使用 ES6,您可以使用箭头函数代替 self
和 bind
:
{
this.state.customers.map((customer, i) => {
return (
<tr key={i}>
<td>
<button onClick={(e) => this.handleClick(customer['id'])}>X</button>
</td>
</tr>
)
})
}
你应该传递给函数onClick
引用
<button onClick={() => console.log("clicked", customerId)}>X</button>
或者如果您不使用箭头功能 ES2015
<button onClick={function () { console.log("clicked", customerId) } }>X</button>
在您的示例中,您正在传递给onClick
undefined
,因为console.log()
返回undefined
,但不引用函数,{}
JSX
上下文中意味着您可以将要执行的 JS 代码传递给它。
Example
相关文章:
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- 单元测试:使用酶模拟父组件中子组件的点击事件
- React/flux - 子组件用户事件 - 是否应通过调度程序路由所有内容
- React:如何侦听子组件事件
- 将事件绑定到其他UI组件's函数,在Kendo MVVM中
- 如何更新angular2中组件之间的事件数据
- 点击tpl链接时,ExtJS 4.2自定义组件触发事件
- 反应:在嵌套组件上冒泡点击事件
- 如何根据其他组件中的事件更新组件URL
- 使用Ember中的组件生命周期事件
- 如何将事件绑定到模式对话框上的组件
- 将事件处理程序推送到父组件
- React,在组件事件上呈现消息的最佳方法
- 如何确定Twitter引导组件事件的来源
- 取消ExtJS组件事件
- Ember:嵌套组件事件冒泡
- 获取飞行组件事件的委托目标
- EmberJS嵌套组件事件
- Angular js文本Angular组件事件上键
- ExtJS“创建”或“初始化”组件事件侦听器