react父子组件之间的传值

本文详细介绍了React中父组件向子组件传递数据的方法,以及子组件如何通过回调函数更新父组件的状态,展示了具体代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

父传子-------------

父组件
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> 

子传父-----------

父组件
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>  
        )
     }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值