React useContext

useContext 允许父组件向其下层无论多深的任何组件提供信息,而无需通过 props 显式传递。

// 1. LevelContext.js  创建 context,将其从文件中导出 
import { createContext } from 'react';
export const LevelContext = createContext(1);

// 2. Section.jsx  提供 context 
import { LevelContext } from './LevelContext.js';
export default function Section({ level, children }) {
  return (
    <section className="section">
      <LevelContext.Provider value={level}>
        {children}
      </LevelContext.Provider>
    </section>
  );
}

// 3. Heading.jsx 使用 Context 
import { useContext } from 'react';
import { LevelContext } from './LevelContext.js';
export default function Heading({ children }) {
  const level = useContext(LevelContext);
  switch (level) {
    case 1:
      return <h1>{children}</h1>;
    case 2:
      return <h2>{children}</h2>;
    case 3:
      return <h3>{children}</h3>;
    default:
      throw Error('未知的 level:' + level);
  }
}

// App.jsx
import Heading from './Heading.js';
import Section from './Section.js';
export default function Page() {
  return (
    <Section level={1}>
      <Heading>主标题</Heading>
      <Section level={2}>
        <Heading>副标题</Heading>
        <Heading>副标题</Heading>
        <Heading>副标题</Heading>
        <Section level={3}>
          <Heading>子标题</Heading>
          <Heading>子标题</Heading>
          <Heading>子标题</Heading>
        </Section>
      </Section>
    </Section>
  );
}

组件会使用 UI 树中在它上层最近的那个 <LevelContext.Provider> 传递过来的值。不是同级,也不是更远的层级。

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-06-18 12:20:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-18 12:20:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-18 12:20:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-18 12:20:02       20 阅读

热门阅读

  1. elementUI实现上传excel文件并传给后端

    2024-06-18 12:20:02       8 阅读
  2. 数据库-单表查询-基本查询

    2024-06-18 12:20:02       7 阅读
  3. GDB使用

    2024-06-18 12:20:02       6 阅读
  4. 量产导入 | ATPG_FLOW

    2024-06-18 12:20:02       10 阅读
  5. 【linux 常用命令】

    2024-06-18 12:20:02       7 阅读
  6. 编程从入门到精通:一段跌宕起伏的旅程

    2024-06-18 12:20:02       8 阅读
  7. 所有报表情况查询明细

    2024-06-18 12:20:02       7 阅读
  8. 【C++】内存管理

    2024-06-18 12:20:02       11 阅读
  9. SQL 入门教程

    2024-06-18 12:20:02       6 阅读
  10. Docker容器技术在Linux平台的应用与实践

    2024-06-18 12:20:02       8 阅读
  11. 【MySQL】——概念、逻辑、物理结构设计

    2024-06-18 12:20:02       8 阅读
  12. vue跨域问题,请注意你的项目是vue2还是vue3

    2024-06-18 12:20:02       9 阅读