首页 > 其他分享 >利用context组件数据传递

利用context组件数据传递

时间:2022-08-23 17:23:50浏览次数:92  
标签:React return 传递 theme context props 组件

 react的数据传递 是从父级向子级传递的。通过props。如果是很多组件需要的数据,通过props传递会非常麻烦。这个时候可以使用context。

context需要可以类似于store但是也不能滥用。

react-redux的 <Provider /> ,就是通过 Context 提供一个全局态的 store ,路由组件react-router通过 Context 管理路由状态等等。

context适用场景:地区偏好,UI主题

传统实现:

class App extends React.Component {
  render() {
    return <Toolbar theme="dark" />;
  }
}

function Toolbar(props) {
  // Toolbar 组件接受一个额外的“theme”属性,然后传递给 ThemedButton 组件。
  // 如果应用中每一个单独的按钮都需要知道 theme 的值,这会是件很麻烦的事,
  // 因为必须将这个值层层传递所有组件。
  return (
    <div>
      <ThemedButton theme={props.theme} />
    </div>
  );
}

class ThemedButton extends React.Component {
  render() {
    return <Button theme={this.props.theme} />;
  }
}
View Code

创建context对象

const MyContext = React.createContext(defaultValue);
创建一个context对象。设置默认值。

当 React 渲染一个订阅了这个 Context 对象的组件,这个组件会从组件树中离自身最近的那个匹配的 Provider 中读取到当前的 context 值。如果没有Provider就会取默认值。

context.Provider

<MyContext.Provider value={默认值}>

每个context对象都返回一个provider组件 

一个provider组件可以和多个消费组件对应关系。多个provider也可以嵌套,里层会覆盖外层。

<ThemeContext.Provider value="dark">
     <Toolbar />
     <ContextTypePage /> //多个组件
</ThemeContext.Provider>

provider值变化 里面所有的消费组件都会渲染。

组件的contextType属性

挂载在 class 上的 contextType 属性会被重赋值为一个 Context 对象。这能让你使用 this.context 来消费最近 Context 上的那个值。你可以在任何生命周期中访问到它。

import {ThemesContext} from './theme-context'

export class ThemedButton extends React.Component{
  render(){
    let props =this.props;
    let theme =this.context;
    console.log(theme)
    return (
      <button
      {...props}
      style={{backgroundColor:theme.background,color:theme.foreground,width:"200px"}}
      />
    )
  }
}
ThemedButton.contextType=ThemesContext;//这个一定要有

简单的例子:

context实现:

// Context 可以让我们无须明确地传遍每一个组件,就能将值深入传递进组件树。
// 为当前的 theme 创建一个 context(“light”为默认值)。
const ThemeContext = React.createContext('light');
class App extends React.Component {
  render() {
    // 使用一个 Provider 来将当前的 theme 传递给以下的组件树。
    // 无论多深,任何组件都能读取这个值。
    // 在这个例子中,我们将 “dark” 作为当前的值传递下去。
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
          <ContextTypePage /> //多个组件
      </ThemeContext.Provider>
    );
  }
}

// 中间的组件不必指明往下传递 theme 。
function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
  // 指定 contextType 读取当前的 theme context。
  // React 会往上找到最近的 theme Provider,然后使用它的值。
  // 在这个例子中,当前的 theme 值为 “dark”。
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}

 

实际应用:

theme-context.js

import React from 'react';
export const themes={
  light:{
    foreground: '#ffffff',
    background:"#4DB8C6"
  },
  dark:{
    foreground: '#ffffff',
    background:"#222222"
  }
}
export const ThemesContext =React.createContext(themes.dark)

themed-button.js

import React from 'react';
import {ThemesContext} from './theme-context'

export class ThemedButton extends React.Component{
  render(){
    let props =this.props;
    let theme =this.context;
    console.log(theme)
    return (
      <button
      {...props}
      style={{backgroundColor:theme.background,color:theme.foreground,width:"200px"}}
      />
    )
  }
}
ThemedButton.contextType=ThemesContext;

app.js

function ToolBar1(props){
  return (
    <ThemedButton onClick={props.changeTheme}>
     主题按钮
    </ThemedButton>
  )
}
class App extends React.Component{
  constructor(props){
    super(props);
    this.state={
      theme:themes.light
    }
    this.toggleTheme = () => {
      this.setState(state => ({
        theme:
          state.theme === themes.dark
            ? themes.light
            : themes.dark,
      }));
      console.log(this.state.theme)
    };
  }
  render (){
    return (
      <ThemesContext.Provider value={this.state.theme}>
      <ToolBar1 changeTheme={this.toggleTheme} />
    </ThemesContext.Provider>
    )
  }
}

 

效果图

 

 

 

 最好实现主题变动的是 改变类名

写两套css样式 根据不同的类名 进行处理。

react官网 https://react.docschina.org/docs/context.html#when-to-use-context

 

标签:React,return,传递,theme,context,props,组件
From: https://www.cnblogs.com/GoTing/p/16616479.html

相关文章

  • 07-React Hooks(路由组件懒加载, Context上下文, 组件优化...)
    扩展setState(1).setState(stateChange,[callback])------对象式的setState1.stateChange为状态改变对象(该对象可以体现出状态的更改)2.callback是可选的......
  • 04-React路由5版本(高亮, 嵌套, 参数传递... )
    React-Router-Dom(路由版本[5])简介React的一个插件库用于实现SPA应用基于React的项目基本都用API<BrowserRouter><HashRouter><Route><Redirect><Link><Na......
  • 01-React基础(JSX, State, Refs, Props组件交互, Event, 生命周期)
    引入JS#react开发JSreact.development.js#reactdom渲染JSreact-dom.development.js#jsx语法转换JSbabel.min.js#参数传值校验JSprop-types.jsJSX语法#......
  • 四大组件之Activity
    关于AndroidManifest.xml先看图吧!这就是android的清单文件!它有什么用呢?前面我们说了,它用于描述项目的对吧!在以前的eclipse项目里,androidmanifest.xml文件里还会有版本......
  • vue3 单文件组件——父组件访问子组件的实例
    如果一个子组件使用的是选项式API 或没有使用 <scriptsetup>,被引用的组件实例和该子组件的 this 完全一致,这意味着父组件对子组件的每一个属性和方法都有完全的访问......
  • vue大文件上传组件选哪个好?
    ​一、概述 所谓断点续传,其实只是指下载,也就是要从文件已经下载的地方开始继续下载。在以前版本的HTTP协议是不支持断点的,HTTP/1.1开始就支持了。一般断点下载时才用到......
  • vue3新内置组件teleport传送门
    使用到的原因:在使用固定定位弹出弹出框的时候,突然遇到位置不正确,而且在有index高级别的情况下依旧位置出错表现如下:出现原因:我的代码出现的tf元素,导致定位祖先元素发......
  • 动态组件的使用
    父组件:<template><divclass="app"><!--动态组件component--><!--is中的组件需要来自两个地方:1.全局注册的组件2.局部注册的组件-->......
  • Vue2按需引入elementUI组件
    按需引入官方文档介绍借助babel-plugin-component,我们可以只引入需要的组件,以达到减小项目体积的目的。首先安装babel-plugin-component:npminstallbabel-plugin-c......
  • Spring 高级 工厂后处理器模拟实现组件扫描-模拟ComponentScan 进阶
    一、自定义Bean后处理器Processorpackagecom.mangoubiubiu.show.a05.component;importcom.mangoubiubiu.show.a05.Config;importorg.springframework.beans.Bea......