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};
}
相关推荐
Monly211 分钟前
【大前端】前期准备-Trae开发工具安装
前端
2601_949720266 分钟前
flutter_for_openharmony手语学习app实战+学习进度实现
javascript·学习·flutter
lllljz13 分钟前
blenderGIS出现too large extent错误
java·服务器·前端
吉吉安14 分钟前
双层文字扫光效果
前端·javascript·css
珑墨16 分钟前
【架构】前端 pnpm workspace详解
前端·架构
小马_xiaoen18 分钟前
WebSocket与SSE深度对比与实战 Demo
前端·javascript·网络·websocket·网络协议
摇滚侠18 分钟前
html,生成一个五行五列的表格,第三列边框是红色,其余列边框是黑色
前端·html
GISer_Jing21 分钟前
从工具辅助到AI开发前端新范式
前端·人工智能·aigc
美狐美颜SDK开放平台21 分钟前
从抖音到私域直播:抖动特效正在重塑直播美颜sdk
前端·人工智能·第三方美颜sdk·视频美颜sdk·美狐美颜sdk
云飞云共享云桌面26 分钟前
SolidWorks如何实现多人共享
服务器·前端·数据库·人工智能·3d