react 跨层级组件传值context

利用 定义一个React.createContext默认值 之后在数据源组件中外层包裹Provider进行传值 之后在接收组件的外层包裹Consumer接收数据回调使用

传值

import React, { Component } from 'react';
import Fa from './fa';
export const ProductContext = React.createContext(0);
export const { Provider, Consumer } = ProductContext;
export default class Grend extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '小饼干',
      index: 0
    };
  }
  changeIndex = () => {
    const { index } = this.state
    this.setState({
      index: index + 1
    })
  }
  render() {
    const { index } = this.state
    return (
      <Provider value={index}>
        <button onClick={this.changeIndex}>报数</button>
        <Fa />
      </Provider>
    )
  }
}

接收

import React, { Component } from 'react';
import { Consumer } from './grend'
export default class Ch extends Component {
  render() {
    return (
      <Consumer>
        {theme =>
          <div>我是{theme}号小饼干</div>
        }
      </Consumer>
    )
  }
}

 

 

 

posted @ 2021-11-19 14:19  fiamme  阅读(303)  评论(0编辑  收藏  举报