[英]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>
)
}
});
呈现此组件后,无需单击任何按钮即可执行console.log调用。
我只想在单击按钮时调用一个方法,没有什么真正复杂的。
这是为什么?
看起来您正在尝试使用addEmailButton
作为customerId
的闭包,但这没有帮助,因为它是需要customerId
参数的处理程序,而不是按钮的呈现。
您所需bind
的就是bind
click事件与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>
)
})
}
您应该将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代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.