【react: createContext 全局变量】

import { createContext, useContext } from "react";

export default function App5() {
  return (
    <div>
      <Section>
        <Heading>标题1</Heading>
        <Section>
          <Heading>标题2</Heading>
          <Section>
            <Heading>标题3</Heading>
            <Section>
              <Heading>标题4</Heading>
              <Section>
                <Heading>标题5</Heading>
                <Section>
                  <Heading>标题6</Heading>
                </Section>
              </Section>
            </Section>
          </Section>
        </Section>
      </Section>
    </div>
  );
}

const levelContext = createContext(0);

const 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>;
    case 4:
      return <h4>{children}</h4>;
    case 5:
      return <h5>{children}</h5>;
    case 6:
      return <h6>{children}</h6>;
    default:
      throw new Error(`Unsupported level: ` + level);
  }
};

// 每次调用会走一遍而不是最终值,这是关键,遇到一次执行一次
const Section = ({ children }) => {
  const level = useContext(levelContext);
  return (
    <section className="section">
      <levelContext.Provider value={level + 1}>
        {children}
      </levelContext.Provider>
    </section>
  );
};

posted @ 2025-06-16 22:26  十三山入秋  阅读(10)  评论(0)    收藏  举报