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};
}
相关推荐
敲敲敲敲暴你脑袋13 分钟前
写个添加注释的vscode插件
javascript·typescript·visual studio code
叁两41 分钟前
用opencode打造全自动公众号写作流水线,AI 代笔太香了!
前端·人工智能·agent
golang学习记1 小时前
GitLens 十大神技:彻底改变你在 VS Code 中的 Git 工作流
前端·后端·visual studio code
SuperEugene1 小时前
后台权限与菜单渲染:基于路由和后端返回的几种实现方式
前端·javascript·vue.js
兆子龙1 小时前
WebSocket 入门:是什么、有什么用、脚本能帮你做什么
前端·架构
csdn飘逸飘逸1 小时前
Autojs基础-全局函数与变量(globals)
javascript
是一碗螺丝粉1 小时前
LangChain 链(Chains)完全指南:从线性流程到智能路由
前端·langchain·aigc
KKKK1 小时前
手写Promise,从测试用例的角度理解
javascript
月弦笙音1 小时前
【浏览器】这几点必须懂
前端
青青家的小灰灰1 小时前
迈向全栈新时代:SSR/SSG 原理、Next.js 架构与 React Server Components (RSC) 实战
前端·javascript·react.js