react中父子组件传值

【父组件】向【子组件】传值

初步使用

  这个是相当容易的,在使用 React 开发的过程中经常会使用到,主要是利用 props 来进行交流。例子如下:

  1.  1 // 父组件
     2 
     3 var MyContainer = React.createClass({
     4 
     5   getInitialState: function () {
     6 
     7     return {
     8 
     9       checked: true
    10 
    11     };
    12 
    13   },
    14 
    15   render: function() {
    16 
    17     return (
    18 
    19       <ToggleButton text="Toggle me" checked={this.state.checked} />
    20 
    21     );
    22 
    23   }
    24 
    25 });
    26 
    27  
    28 
    29 // 子组件
    30 
    31 var ToggleButton = React.createClass({
    32 
    33   render: function () {
    34 
    35     // 从【父组件】获取的值
    36 
    37     var checked = this.props.checked,
    38 
    39         text = this.props.text;
    40 
    41  
    42 
    43     return (
    44 
    45         <label>{text}: <input type="checkbox" checked={checked} /></label>
    46 
    47     );
    48 
    49   }
    50 
    51 });

    如果组件嵌套层次太深,那么从外到内组件的交流成本就变得很高,通过 props 传递值的优势就不那么明显了。

    

// 父组件

var MyContainer = React.createClass({

  render: function() {

    return (

      <Intermediate text="where is my son?" />

    );

  }

});

 

// 子组件1:中间嵌套的组件

var Intermediate = React.createClass({

  render: function () {

    return (

      <Child text={this.props.text} />

    );

  }

});

 

// 子组件2:子组件1的子组件

var Child = React.createClass({

  render: function () {

    return (

      <span>{this.props.text}</span>

    );

  }

});

猜你喜欢

转载自www.cnblogs.com/12345l/p/12116324.html