React Context realizes the basic use of cross-level data transfer

Context function:
Provides a method to transfer data between component trees without manually adding props for each layer of components

import styles from './index.less';
import React, {
    
     Component, createContext } from 'react'

const BatteryContext = createContext(0);
//创建createContext实例对象,必须传一个默认值,默认值的意义就是Consumer向上找不到对于的Provider就会展示该默认值
const OnlineContext = createContext(false);

class Leaf extends Component {
    
    
  render() {
    
    
    return (
      <BatteryContext.Consumer>
        {
    
    
          battery => (
            <OnlineContext.Consumer>
              {
    
    
                online => <h1 className={
    
    styles.title}>Battery:{
    
    battery},Online:{
    
    String(online)}</h1>
              }
            </OnlineContext.Consumer>
          )
        }
      </BatteryContext.Consumer>
      // Consumer用于接收Provider提供的变量值
      // 在Consumer不能直接渲染其他组件,必须声明一个函数,改函数的唯一参数就是BatteryContext的value值
    )
  }
}

class Middle extends Component {
    
    
  render() {
    
    
    return <Leaf />
  }
}

export default class IndexPage extends Component {
    
    
  state = {
    
    
    online: false,
    battery: 60,
  };
  render() {
    
    
    const {
    
     battery, online } = this.state;
    return (
      <div>
        <BatteryContext.Provider value={
    
    battery}>
          <OnlineContext.Provider value={
    
    online}>
            <button type="button" onClick={
    
    () => this.setState({
    
     battery: battery - 1 })}>Press</button>
            <button type="button" onClick={
    
    () => this.setState({
    
     online: !online })}>Switch</button>
            <Middle />
          </OnlineContext.Provider>
        </BatteryContext.Provider>
        {
    
    /* BatteryContext对象 派生出 “Provider”生产者 和 “Consumer 消费者” */}
        {
    
    /* BatteryContext对象必须要有一个值 */}
        {
    
    /* 当BatteryContext对象的value值改变,就会跨域层级,提醒Consumer进行重渲染 */}
        {
    
    /* 如果有多个Context,直接嵌套起来即可,顺序不重要 */}
      </div>
    );
  }
}

Guess you like

Origin blog.csdn.net/weixin_44745920/article/details/114909343