美文网首页
React父组件与子组件之间的值传递

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

作者: ZZES_ZCDC | 来源:发表于2017-11-27 16:22 被阅读13041次

    整体代码地址:
    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

    相关文章

      网友评论

          本文标题:React父组件与子组件之间的值传递

          本文链接:https://www.haomeiwen.com/subject/cbzrbxtx.html