zoukankan      html  css  js  c++  java
  • react 组件传值

      通常组件之间的传值除了 localStorage、sessionStorage 以及利用 url 之前,就是状态管理,还可以直接的通过 组件之间相互的传值;

    父组件传值子组件

      父组件传值给子组件一般是利用 props 进行传值;就是在父组件中引用子组件的时候,在上边绑定一个属性,这个跟 vue 其实是一样的,只不过 vue  是直接通过 props 接收的,而 react 是在constructor 中,super 中接收 props 然后就可以直接通过 this.props 进行获得了;例如:

    // 父组件
        <child-com data='这是父组件的值'>
    
    // 子组件
        class chidl extends React.Component {
            constructor(props) {  } 
           render(){
              console.log(this.props.data)
              return ()
           }       
       }
    

     子组件传值给父组件

      在 react 中子组件传值给父组件是和 vue 一样的,都是通过回调函数的方式,只不过在 vue 中是通过 $emit 的方式,而在 react 中是通过 this.props 获取到父组件的方法,然后通过传参实现;例如:

    // 父组件
       class parent extends React.Component {
            constructor(props) { 
               this.state = {
                   data: ''
               }
            } 
            dataChange (data) { consle.log(data) }
           render(){
              return (
                   <child-com  dataEvent={ data => this.dataChange(data) }>
               )
           }       
       }  
    
       
    // 子组件
        class chidl extends React.Component {
            constructor(props) {  } 
           render(){
              return (
                <div onClick={() => this.props.dataEvent('这是子组件') }></div>
              )
           }       
       } 
    

    兄弟组件之间的传值

      一般情况下兄弟组件之间的传值,如果有共同的父级组件就可以通过父级组件进行传值,或者是构造第三方父组件进行实现,但是对于多层的父组件传值这样就比较麻烦了,这样的情况一般情况下我们都会考虑使用状态管理或者 web 存储来实现

  • 相关阅读:
    The Best Seat in ACM Contest
    确定比赛名次
    Red and Black
    Can you find it?
    胜利大逃亡
    Reward
    DXUT编译指南(转)
    逐顶点和逐像素光照
    转战DX
    hlsl之ambient
  • 原文地址:https://www.cnblogs.com/mufc/p/11339772.html
Copyright © 2011-2022 走看看