Step 1.创建 context :
import { createContext } from 'react';
export const LevelContext = createContext(1);
Step 2:使用 Context :
从 React 中引入 useContext
Hook 以及你刚刚创建的 context:
import { useContext } from 'react';
import { LevelContext } from './LevelContext.js';
export default function Heading({ children }) {
const level = useContext(LevelContext);
// ...
}
Step 3:提供 context :
import { LevelContext } from './LevelContext.js';
export default function Section({ level, children }) {
return (
<section className="section">
<LevelContext.Provider value={level}>
{children}
</LevelContext.Provider>
</section>
);
}