2015-12-03 91 views
0

我有一個組件的父子關係,我正在嘗試設置。我希望讓父母保持對交易原始狀態(React組件)的瞭解,然後根據是否小於原始金額確定是否允許添加新交易。點擊通話時,我不知道如何正確地將數據從組件傳遞到組件。下面列出了我的原始組件。請發送幫助!反應 - 將變量傳遞給另一個組件

```

var transaction = React.createClass({ 
     getInitialState: function(){ 
     return { 
      transactions: [ { desc: '', val: 0 } ], 
      initialTransaction: 10 
     } 
     }, 
     render: function(){ 
     return (
      <div> 
      { this.state.transactions.map(this.renderChild) } 
      <button onClick={ this.newTransaction }>Add</button> 
      </div> 
     ) 
     }, 
     shouldComponentUpdate: function(nextProps, nextState) { 
     console.log(nextState.transactions); 
     return nextState.transactions.reduce(function(a, b) { 
      return { val: a.val + b.val} 
     }) == this.state.initialTransaction 
     }, 
     newTransaction: function(_transaction,x,y){ 
     this.state.transactions.push(_transaction); 

     this.setState({ 
      transactions: this.state.transactions 
     }); 
     this.forceUpdate(); 
     }, 
     renderChild: function(_transaction){ 
     return (
      <div> 
      <input type='text' defaultValue={ _transaction.desc } /> 
      <input type='text' defaultValue={ _transaction.val }/> 
      // TODO: this button should pass a transaction up to the parent component 
      </div> 
     ); 
     } 
    }); 
    React.renderComponent(<transaction />, document.getElementById('mount-point')); 

```

回答

1

你可以傳遞一個回調。

在父:

onTransaction: function(transaction) { 
    console.log('onTransaction', transaction); 
} 

並將它傳遞給子元素:

<Transaction onTransaction={this.onTransaction} ... /> 

在孩子,你那麼可以通過this.props.onTransaction調用這個方法:

renderChild: function(_transaction) { 
    ... 
    <button onClick={() => this.props.onTransaction(_transaction)} /> 
+0

確定,所以可以說我不想在每個子元素上都有那個按鈕。我想有一個'添加'按鈕,向數組添加一個新的事務,然後讓孩子重新呈現,以便從那裏獲取所有新元素。我會怎麼做? – noname

+0

另外,在renderChild調用中提到的'this'是什麼? 'this'的道具元素是什麼? – noname