2014-03-03 49 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