美文网首页
Context API

Context API

作者: kzc爱吃梨 | 来源:发表于2021-06-30 11:05 被阅读0次

Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。

在根部套一个const ThemeContext = React.createContext('light')的标签

import React from "react";

const ThemeContext = React.createContext('light');
class App extends React.Component {
  render() {
    // 使用一个 Provider 来将当前的 theme 传递给以下的组件树。
    // 无论多深,任何组件都能读取这个值。
    // 在这个例子中,我们将 “dark” 作为当前的值传递下去。
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </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} />;
  }
}

function Button(props) {
  return (
    <div>{props.theme}</div>
  )
}
效果图

挂载在 class 上的 contextType 属性会被重赋值为一个由 React.createContext() 创建的 Context 对象。此属性能让你使用 this.context 来消费最近 Context 上的那个值。你可以在任何生命周期中访问到它,包括 render 函数中。

相关文章

  • Context API

    Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。 在根部套一个co...

  • Android 6.0以下摄像头权限

    不可行权限判断API: context.checkCallingPermission context.checkC...

  • vue使用技巧

    1.require.context() 父组件中导入多个组件 使用require.context() api描述:...

  • 9天深入react(2-1)-Context

    组件跨层级通讯-Context Context API React.createContext 创建一个Con...

  • 前端工程化知识零散学习(面试篇)

    require.context() require.context()是一个webpack的api,主要作用是批量...

  • getSystemService

    getSystemService是在Context这个类下的方法,进入Api查询界面搜索Context,然后找到 ...

  • getSystemService

    getSystemService是在Context这个类下的方法,进入Api查询界面搜索Context,然后找到 ...

  • react Context API

    一个简单的四层函数参数传递的demo 原生js写法 上面的代码我如果要在每个函数里拿到n就需要一直把n作为参数传递...

  • 【React】Context API

    参考链接:【https://medium.com/search?q=ReactContext】 在嵌套组件中我们常...

  • iOS 绘图学习实战(一) -- 绘图基础

    1. 使用Quartz的API 创建Context,并且绘图 完全使用Quartz创建Context, 并且使用Q...

网友评论

      本文标题:Context API

      本文链接:https://www.haomeiwen.com/subject/gsrkultx.html