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>
)
}
});
渲染此组件时,将执行 console.log 调用,而无需单击任何按钮。
我只想在单击按钮时调用一个方法,没什么复杂的。
这是为什么?
最佳答案
看起来您正在尝试使用 addEmailButton
作为 customerId
的闭包,但这没有帮助,因为它是需要 customerId 的处理程序
参数,而不是按钮的呈现。
您所需要做的就是使用 customerId
参数绑定(bind)
点击事件:
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>
)
})
}
关于javascript - React 渲染组件会触发 onClick 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361850/