2014-03-03 63 views
3

我試圖用React打包語義UI元素,以便它們可以在我的應用程序中重用。ReactJS:在父項中訪問子組件屬性

var s_input = React.createClass({ 
     render: function(){ 
      return this.transferPropsTo(
       <div className = "ui input"> 
        <input type="text" placeholder={this.props.placeHolderTxt} ref="text"/> 
       </div> 
      ) 
     } 
    }); 

我使用的輸入組件內從:

<form onSubmit={this.handleSubmit} method="POST"> 
    <s_input placeHolder={this.props.placeHolderTxt||''}></s_input> 
</form> 

這是我的handleSubmit方法:

handleSubmit:function(e){ 
    e.preventDefault(); 
    var text = this.refs.text.getDOMNode().value.trim(); 
       this.refs.text.getDOMNode().value = ''; 
       this.props.onSubmit(text); 
} 

我正試圖訪問文本的問題輸入組件的屬性,以便我可以執行類似的操作。有沒有人知道如何去做這件事。

+0

您能否顯示完整的'handleSubmit()'方法? – cantera

+0

我編輯了這個問題,幷包含我的代碼handleSubmit() – nimgrg

回答

3

你可以做類似

var input = React.createClass({ 
    render: function(){ 
     return this.transferPropsTo(
      <div className = "ui input"> 
       <input className="ui input" type="text" placeHolder={this.props.placeHolderTxt} ref="text"/> 
      </div> 
     ) 
    }, 
    getValue: function() { 
     return this.refs.text.getDOMNode().value; 
    } 
}); 

然後,你可以做<s_input ref="myinput" />this.refs.myinput.getValue()。你也可以構造你的代碼來傳遞一個onChange回調,然後讀取e.target.value,就像處理任何其他受控組件一樣:http://facebook.github.io/react/docs/forms.html

+0

謝謝!適合我! – nimgrg