React - 将变量传递给另一个组件

时间:2015-12-03 05:07:04

标签: javascript reactjs

我为尝试设置的组件建立了父子关系。我希望让父母保留对事务原始状态(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 个答案:

答案 0 :(得分:1)

您可以传递回调。

在父母:

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

并将其传递给子元素:

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

在孩子中,您可以通过this.props.onTransaction

调用此方法
renderChild: function(_transaction) {
  ...
  <button onClick={() => this.props.onTransaction(_transaction)} />