2016-04-11 17 views
3

私は、リストから生成されたアイテム(マップ機能付き)を持つこのReactコンポーネントを持っています。これらの各要素にはボタンがあります。このボタンの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

オリジナル受け入れ答え:

することはできだけでは、脂肪の矢印の機能を使用するかpass in thisArgまたは必要しかし、あなたはmapコールバックでレンダリングされているので、例を反応させるのようなthis上の機能にbind

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'は2番目のイベント引数を 'function(item、event)'として取り、 'event.preventDefault ) '。 – Aaron

関連する問題