React父组件与子组件之间的值传递

整体代码地址:
https://github.com/klren0312/react_study/blob/master/stu15/src/Father.js
https://github.com/klren0312/react_study/blob/master/stu15/src/Son.js

一、父组件向子组件传递信息

将父组件的state通过props传入子组件

父组件代码片段

 
  constructor(props){
    super(props)
    this.state={
      message:"我是父组件传来的"
    }
  }
  render(){
    return(
      <div style={{background:"red",padding:"30px"}}>
          <Son msg={this.state.message}/>
      </div>
    )
  }
}

子组件代码片段

<div>
   父组件传到子组件的信息:<span style={{background:"white"}}>{this.props.msg}</span>
</div>  

效果

图片.png

二、子组件向父组件传递数据

父组件代码片段

constructor(props){
    super(props)
    this.state={
      visible:false,
    }
  }
  /**
   * 进入
   */
  goIn(){
    this.setState({
      visible:true
    })
  }
  /**
   * 取消
   * @param mode true/false
   */
  cancel(mode){
    console.log(mode)
    this.setState({
      visible:mode
    })
  }
  render(){
    return(
      <div style={{background:"red",padding:"30px"}}>
      {
        this.state.visible ?
        <div style={{background:"yellow"}}>
          <Son cancel={mode=>this.cancel(mode)}/>
        </div>
        :
        <div style={{background:"blue"}}>
          <button onClick={this.goIn.bind(this)} style={{width:"100px",height:"50px"}}>进入</button>
        </div>
      }
      </div>
    )
  }

子组件代码片段

class Son extends React.Component{
  render(){
    console.log(this.props.msg)
    return(
      <div>
        <button style={{width:"100px",height:"50px"}} onClick={()=>{this.props.cancel(false)}}>返回</button>
        父组件传到子组件的信息:<span style={{background:"white"}}>{this.props.msg}</span>
      </div>  
    )
  }
}

效果

fefe.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文: https://github.com/ecomfe/spec/blob/master/javascript...
    zock阅读 3,408评论 2 36
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,624评论 25 708
  • 今天是农历的霜降,在福建似乎刚刚立秋的味道,走在山边的小路上,感受柔和的阳光,和煦的秋风带来淡淡桂花的香气,当然还...
    隐者_bf0f阅读 684评论 0 0
  • 儿子平时调皮,任性,话多,突然发现这其实是他的优点,男孩子嘛,不调皮,我肯定着急,任性也可叫做专注,话多那是想发表...
    TIM陈志浩阅读 156评论 0 0
  • 卡夫卡这个名字近一两年常常听人提起,对我而言,却是一个着实陌生的人,恰好这本书后面有厚厚的附录,有密伦娜的闺蜜之女...
    考拉浅浅笑阅读 450评论 0 1