react-进阶系列-实现react-redux的provider

不用provider,爷爷组件传递属性给孙子组件

三个嵌套组件:Grandfather Fther Child
如果 Child 想要拿到最外层 Grandfather 的属性,就必须Grandfather–Fater–Child这样一层一层传递下来,
不仅麻烦,而且一旦中途传递出错,最后一层组件拿到的也是错误的

  • grandfather.js
class Child extends React.Component {
  state = {
    age : 66
  }
  render(){
      return (
      <div>
          <Father age = {this.state.age}>
      </div>)
  }
     
}

  • father.js
class Father extends React.Component {
 
  render(){
      return (
      <div>
          <Child age = {this.props.age}> 
      </div>)
  }
     
}

  • child.js
class Child extends React.Component {
  render(){
      return (
      <div>
          {this.props.age} // 经过一层层传递拿到 grandfather.js的age值
      </div>)
  }
     
}

上面方法可知一层一层传递非常麻烦

实现一个provider简化属性传递

利用react的context实现一个provider,不用一层层传递,孙子组件直接通过context取到爷爷组件的属性

  • app.js
import Provider from './provider'
import Child from './child';

 <Provider info={{name:'max', age: 13}}>
          <Child/>
 </Provider>

  • Provider.js

npm i prop-types --save 安装需要的包

import React, { Component,Children } from 'react';
import PropTypes from  "prop-types" 
import Child from './child'

class Provider extends React.Component {
//必须定义这个对象
  static  childContextTypes = {
    store:PropTypes.object.isRequired
  };
  constructor(props){
      super(props)
      // 获取传给Provider组件的属性
      this.store = {...props}
  }
  //设置上下文的公共内容 
  // 这样设置以后,Provider下面的子组件,孙子组件就可以this.context.store拿到所有Provider包含的属性
  getChildContext(){
    return {store:this.store}
  }
  render(){
      return (
      <div>
          <Child/>
      </div>)
  }  
}

export default Provider;

  • child.js
import React, { Component } from 'react';
import PropTypes from  "prop-types"

class Child extends React.Component {
  // 必须要申明,react认为全局变量不好
  static  contextTypes = {
    store:PropTypes.object.isRequired
  };
  render(){
      return (
      <div>
          <h1>{this.context.store.info.age}</h1>  // 这里直接获取provider提供的属性值
      </div>)
  }

     
}

export default Child;


猜你喜欢

转载自blog.csdn.net/qq1498982270/article/details/88669515