react 组件间参数传递

基础用法、父子通信
①传值
<MyHeader myTitle="这是登录页面">
</MyHeader>
②接收
在MyHeader组件中接收通过myTitle属性给 传递的数据
this.props.myTitle
 var MyHeader = React.createClass({
       render:function(){
         return <h2>
          {this.props.myTitle}
         </h2>
       }
     })


     ReactDOM.render(
       <MyHeader  myTitle="这是标题内容"></MyHeader>,
       document.getElementById('example')
     )
父与子通信
在react中,可以通过自定义属性传一个普通的字符串,还可以传一个方法

子与父通信的标准版流程:
①父定义一个有参数的方法
rcv:function(msg){}
②将此方法传递给子组件
<son func={this.rcv}></son>
③子组件来调用由参数方法,将数据传递到父组件
this.props.func(123)
 var MyButton = React.createClass({
      handleClick:function(){
        this.props.func(10)
      },
      render:function(){
        return <button 
        onClick={this.handleClick}>{this.props.btnText}</button>
      }
    })

    var MyCart = React.createClass({
      funcDel:function(index){
        alert('下标为'+index+'的商品删除成功')
      },
      funcSubmit:function(){
        alert('结算成功')
      },
      render:function(){
        return <div>
         <MyButton btnText="删除" func={this.funcDel}></MyButton>
         <MyButton btnText="结算" func={this.funcSubmit}></MyButton>
        </div>
      }
    })
    
    ReactDOM.render(
       <MyCart></MyCart>,
       document.getElementById('example')
     )
兄弟通信
ReactJS中 并没有直接提供兄弟通信的解决方案:
借助于共同的父组件来完成兄弟通信过程

this.props.children
组件类this.props对象中的keyValue,和调用组件时所指定的属性是一一对应的;其实有一个例外:this.props.children

可以通过this.props.children来获取到组件在被调用时 内部的子元素

注意事项:
this.props.children类型是不确定的,如果一个字标签都没有:undefined
如果只有一个:object
如果有多个:array

React中实现一个方法来方便的遍历this.props.children:

React.Children.map(
this.props.children,
(value)=>{
return value
}
)


猜你喜欢

转载自www.cnblogs.com/iamlhr/p/10906233.html