(reactjs)获取子组件值

时间:2016-07-28 10:20:01

标签: javascript reactjs properties

我有以下反应组件Timepicker:

/usr/local/lib/python2.7/dist-packages/django/template/utils.py:37:
RemovedInDjango110Warning: You haven't defined a TEMPLATES setting. You must 
do so before upgrading to Django 1.10. Otherwise Django will be unable to load 
templates. "unable to load templates.", RemovedInDjango110Warning)

SingleTask使用TimePicker:

export default class TimePicker extends Component{

 render(){
   return(
     <div>
      <input id={this.props.nameID} type="text"></input>
      </div>);
 }
}  

如何从SingleTask访问TimePicker中的输入值?

1 个答案:

答案 0 :(得分:1)

您可以通过两种方式解决此问题:

  1. 仅更改SingleTask组件: 添加一个参考 TimePicker 组件并访问它的DOM。从那里,您可以通过选择jQuery选择器来查询输入。这里我使用了标签选择器(注意:没有包含jQuery的依赖关系)。
  2. export default class SingleTask extends Component{ 
      yourFunction(){
        var selectedTime = React.findDOMNode(this.refs.timePickerComp).querySelector('input').value;
       }
      render(){
         ....
         <TimePicker ref="timePickerComp" nameID="time" />
        .....
      }
    } 
    
    1. 通过子组件的功能公开数据(The React方式):
    2. TimePicker:

      export default class TimePicker extends Component{
      function getSelectedTime(){
       return document.getElementById(this.props.nameID).value;
      }
       render(){
         return(
           <div>
            <input id={this.props.nameID} type="text"></input>
            </div>);
       }
      }  
      

      SingleTask:

      export default class SingleTask extends Component{
         yourFunctionWhereYouNeedTime(){
          var timeSelected = this.refs.timePickerComp.getSelectedTime(); // here you'll access the child component data.
         }
         render(){
           ....
           <TimePicker ref="timePickerComp" nameID="time" />
          .....
        }
      }