2016-04-11 42 views
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組件中。

我該怎麼做?

回答

9

原始接受的答案:

您可以bind到就像陣營例子,但是因爲你在其中呈現map回調,你需要或者pass in thisArg或使用脂肪箭頭功能上this功能:

var Component = React.createClass({ 
    assignItem: function(item){ 
     this.setState({item:item}) 
    }, 
    render: function(){ 
     // bind to this.assignItem 
     var listItems = list.map(function(item){ 
      return <div>{item} 
       <button onClick={this.assignItem.bind(this, item)}>Click</button> 
      </div> 
     }, this); // pass in this, or use fat arrow map callback 
     return <div>{listItems}</div> 
    } 
}) 

更新2017年:

這是使用old React API和相應的舊的答案一個老問題。今天你應該使用class or functional React component API。要傳遞參數以單擊處理程序,您只需編寫一個內聯fat arrow function並使用所需的任何參數進行調用。上面的例子結束了這樣的:

class MyComponent extends React.Component { // or React.PureComponent 
    assignItem = item => { // bound arrow function handler 
     this.setState({ item: item }); 
    } 
    render() { 
     var listItems = list.map(item => { 
      // onClick is an arrow function that calls this.assignItem 
      return <div>{item} 
       <button onClick={e => this.assignItem(item)}>Click</button> 
      </div> 
     }); 
     return <div>{ listItems }</div> 
    } 
} 

注:assignItem處理程序必須的束縛,這是使用箭頭用作class property在這裏完成。

+0

優秀!這麼簡單,它的工作!非常感謝。 –

+0

'bind'將預先加入參數,但仍然傳遞原始參數,所以'assignItem'可以將第二個事件arg作爲'function(item,event)'並調用'event.preventDefault( )'。 – Aaron