3
我有這個React組件,它具有從列表(使用map函數)生成的項目。每個元素都有一個按鈕。我想讓這個按鈕的onclick按鈕傳入一個參數來確定哪個列表項的按鈕被點擊了。在ReactJS中傳遞參數onclick
它看起來像這樣。
var Component = React.createClass({
assignItem: function(item){
this.setState({item:item})
},
render: function(){
var listItems = list.map(function(item){
return <div>{item}
<button onClick={this.assignItem(item)>Click</button>
</div>
})
return <div>{listItems}</div>
}
})
當然,這是行不通的。錯誤消息說this.assignItem不是一個函數。 我知道官方的陣營文檔建議是:
var handleClick = function(i, props) {
console.log('You clicked: ' + props.items[i]);
}
function GroceryList(props) {
return (
<div>
{props.items.map(function(item, i) {
return (
<div onClick={handleClick.bind(this, i, props)} key={i}>{item}</div>
);
})}
</div>
);
}
ReactDOM.render(
<GroceryList items={['Apple', 'Banana', 'Cranberry']} />, mountNode
);
但與函數工作在組件的外面。因爲我想讓我的函數操作狀態,所以我想將它保留在React組件中。
我該怎麼做?
優秀!這麼簡單,它的工作!非常感謝。 –
@MariePelletier,如果我返回標記,那麼我還需要防止默認。如何將事件傳遞給assignItem?或者我應該總是使用
'bind'將預先加入參數,但仍然傳遞原始參數,所以'assignItem'可以將第二個事件arg作爲'function(item,event)'並調用'event.preventDefault( )'。 – Aaron