当前位置: 移动技术网 > IT编程>开发语言>JavaScript > react-父子子孙组件嵌套-context

react-父子子孙组件嵌套-context

2020年01月17日  | 移动技术网IT编程  | 我要评论

方案一

import react from 'react'
import reacttypes from 'prop-types'

/* // 最外层的父组件
export default class com1 extends react.component {
  constructor(props) {
    super(props)

    this.state = {
      color: 'red'
    }
  }

  render() {
    return <div>
      <h1>这是 父组件 </h1>
      <com2 color={this.state.color}></com2>
    </div>
  }
}



// 中间的子组件
class com2 extends react.component {
  render() {
    return <div>
      <h3>这是 子组件 </h3>
      <com3 color={this.props.color}></com3>
    </div>
  }
}


// 内部的孙子组件
class com3 extends react.component {
  render() {
    return <div>
      <h5 style={{ color: this.props.color }}>这是 孙子组件 </h5>
    </div>
  }
} */

方案二:用context

context特性

记住一串单词组合getchildcontexttypes
前3个、后3个、后两个
一个方法、两个静态属性

import react from 'react'
import reacttypes from 'prop-types'

// 最外层的父组件
export default class com1 extends react.component {
  constructor(props) {
    super(props)

    this.state = {
      color: 'red'
    }
  }

  //   getchildcontexttypes
  // 1. 在 父组件中,定义一个 function,这个function 有个固定的名称,叫做 getchildcontext ,内部,必须 返回一个 对象,这个对象,就是要共享给 所有子孙组件的  数据
  getchildcontext() {
    return {
      color: this.state.color
    }
  }

  // 2. 使用 属性校验,规定一下传递给子组件的 数据类型, 需要定义 一个 静态的(static) childcontexttypes(固定名称,不要改)
  static childcontexttypes = {
    color: reacttypes.string // 规定了 传递给子组件的 数据类型
  }


  render() {
    return <div>
      <h1>这是 父组件 </h1>
      <com2></com2>
    </div>
  }
}



// 中间的子组件
class com2 extends react.component {
  render() {
    return <div>
      <h3>这是 子组件 </h3>
      <com3></com3>
    </div>
  }
}



// 内部的孙子组件
class com3 extends react.component {

  // 3. 上来之后,先来个属性校验,去校验一下父组件传递过来的 参数类型
  static contexttypes = {
    color: reacttypes.string // 这里,如果子组件,想要使用 父组件通过 context 共享的数据,那么在使用之前,一定要先 做一下数据类型校验
  }

  render() {
    return <div>
      <h5 style={{ color: this.context.color }}>这是 孙子组件  ---  {this.context.color} </h5>

    </div>
  }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网