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};
}
相关推荐
她似晚风般温柔7892 小时前
Uniapp + Vue3 + Vite +Uview + Pinia 分商家实现购物车功能(最新附源码保姆级)
开发语言·javascript·uni-app
Jiaberrr3 小时前
前端实战:使用JS和Canvas实现运算图形验证码(uniapp、微信小程序同样可用)
前端·javascript·vue.js·微信小程序·uni-app
everyStudy3 小时前
JS中判断字符串中是否包含指定字符
开发语言·前端·javascript
城南云小白3 小时前
web基础+http协议+httpd详细配置
前端·网络协议·http
前端小趴菜、3 小时前
Web Worker 简单使用
前端
web_learning_3213 小时前
信息收集常用指令
前端·搜索引擎
Ylucius3 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
tabzzz3 小时前
Webpack 概念速通:从入门到掌握构建工具的精髓
前端·webpack
200不是二百4 小时前
Vuex详解
前端·javascript·vue.js
滔滔不绝tao4 小时前
自动化测试常用函数
前端·css·html5