[英]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.