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> 传递过来的值。不是同级,也不是更远的层级。