2014-01-10 34 views
7

我試圖讓通過另一個組件呈現的按鈕引用和/或影響不同組件的狀態。另一個組件中的React JS引用函數

var Inputs = React.createClass({ 
    getInitialState: function(){ 
    return {count: 1}; 
    }, 
    add: function(){ 
    this.setState({ 
     count: this.state.count + 1 
    }); 
    }, 
    render: function(){ 
    var items = []; 
    var inputs; 
     for (var i = 0; i < this.state.count; i++){ 
     items.push(<input type="text" name={[i]} />); 
     items.push(<br />); 
     } 
    return (
     <div className="col-md-9"> 
     <form action="/" method="post" name="form1"> 
      {items} 
      <input type="submit" className="btn btn-success" value="Submit Form" /> 
     </form> 
     </div> 
    ); 
    } 
}); 

我想寫一個新組件,它將能夠訪問輸入中的添加功能。我試圖直接與Inputs.add像這樣引用它:

var Add = React.createClass({ 
    render: function(){ 
    return (
     <input type="button" className="btn" value="Add an Input" onClick={Inputs.add} /> 
    ); 
    } 
}); 

但沒有奏效。我如何能夠通過另一個組件訪問組件的功能,或者通過另一個組件來影響組件的狀態?謝謝。

回答

9

您可以通過創建一個負責管理狀態的父組件,然後將狀態向下推到子組件作爲道具來實現。

/** @jsx React.DOM */ 

var Inputs = React.createClass({ 

    render: function() { 
     var items = []; 
     var inputs; 
     for (var i = 0; i < this.props.count; i++) { 
      items.push(<input type="text" name={[i]} />); 
      items.push(<br />); 
     } 
     return ( 
      <div className = "col-md-9"> 
       <form action = "/" method = "post" name = "form1"> 
        {items} 
        <input type="submit" className="btn btn-success" value = "Submit Form" />    
       </form> 
      </div> 
     ); 
    } 
}); 

var Add = React.createClass({ 
    render: function() { 
     return (<input type = "button" className="btn" value="Add an Input" onClick={this.props.fnClick}/>); 
    } 
}); 

var Parent = React.createClass({ 
    getInitialState: function(){ 
     return {count:1} 
    }, 
    addInput: function(){ 
     var newCount = this.state.count + 1; 
     this.setState({count: newCount}); 
    }, 
    render: function(){ 
     return (
      <div> 
       <Inputs count={this.state.count}></Inputs> 
       <Add fnClick={this.addInput}/> 
      </div> 
     ); 
    } 
}); 

React.renderComponent(<Parent></Parent> , document.body); 

jsFiddle

+1

我已經設置了父子組件設置,但遇到了讓孩子使用父母功能的細節問題。這個答案幫助我通過了作爲道具方法的功能,所以謝謝。 – redlena

1

你可以調用的renderComponent返回值的功能:

var Inputs = React.createClass({…}); 
var myInputs = React.renderComponent(Inputs); 
myInputs.add(); 

只有這樣,才能得到一個處理一個陣營組件實例之外的陣營是由存儲返回React.renderComponent的值。 Source

相關問題