React Context的使用方法

背景:在某些场景下,你想在整个组件树中传递数据,但却不想手动地在每一层传递属性,你可以直接在React中使用强大的contextAPI 解决上述问题

在一个典型的React 中,数据通过Props属性自下而上(由父及子)进行传递的,但这种做法对于某些类型的属性而言机器繁琐,(地区偏好,UI主题)这些属性是应用程序中许多组件都需要的。Context提供了一种在组件之间共享此值的方式,而不必显式的通过组件树逐层传递props

contextType只能用在类组件里

Consumer一般用在函数组件中

javascript 复制代码
import React from './react';
import ReactDOM from './react-dom';
let ThemeContext = React.createContext();
/* let ThemeContext = React.createContext();
let { Provider, Consumer } = ThemeContext; */
//ThemeContext={Provider,Consumer} Consumer一般用在函数组件中
function Header(){
  return (
    <ThemeContext.Consumer>
      {
        value=>(
          <div style={{ margin: '10px', border: `5px solid ${value.color}`, padding: '5px' }}>
            头部
          </div>
        )
      }
    </ThemeContext.Consumer>
  )
}
class Main extends React.Component {
  static contextType = ThemeContext
  render() {
    return (
      <div style={{ margin: '10px', border: `5px solid ${this.context.color}`, padding: '5px' }}>
        主体
        <Content />
      </div>
    )
  }
}
class Content extends React.Component {
  static contextType = ThemeContext
  render() {
    return (
      <div style={{ margin: '10px', border: `5px solid ${this.context.color}`, padding: '5px'}}>
        内容
        <button onClick={()=>this.context.changeColor('red')}>变红</button>
        <button onClick={()=>this.context.changeColor('green')}>变绿</button>
      </div>
    )
  }
}
class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: 'red' };
  }
  changeColor = (color) => {
    this.setState({ color });
  }
  render() {
    let contextValue = { color: this.state.color, changeColor: this.changeColor };
    return (
      <ThemeContext.Provider value={contextValue}>
        <div style={{ margin: '10px', border: `5px solid ${this.state.color}`, padding: '5px', width: '200px' }}>
          主页
           <Header />
          <Main />
        </div>
      </ThemeContext.Provider>
    )
  }
}
ReactDOM.render(<Page />, document.getElementById('root'));

react.js中相关代码

javascript 复制代码
function createContext(){
    function Provider({value,children}){
        Provider._value = value;
        return children;
    }
    function Consumer({children}){
       return children(Provider._value);
    }
    return {Provider,Consumer};
}
相关推荐
excel4 小时前
ES6 中函数的双重调用方式:fn() 与 fn\...``
前端
可乐爱宅着4 小时前
全栈框架next.js入手指南
前端·next.js
你的人类朋友6 小时前
什么是API签名?
前端·后端·安全
会豪8 小时前
Electron-Vite (一)快速构建桌面应用
前端
中微子8 小时前
React 执行阶段与渲染机制详解(基于 React 18+ 官方文档)
前端
唐某人丶8 小时前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
中微子8 小时前
深入剖析 useState产生的 setState的完整执行流程
前端
遂心_8 小时前
JavaScript 函数参数传递机制:一道经典面试题解析
前端·javascript
小徐_23338 小时前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
RoyLin9 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js