代码示例
import React, { useContext } from 'react';
// 创建一个 context 对象
const ThemeContext = React.createContext('light');
// 父组件
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
// 子组件
function Toolbar() {
// 使用 useContext 获取当前的 context 值
const theme = useContext(ThemeContext);
return (
<div style={{ backgroundColor: theme === 'dark' ? 'black' : 'white', color: theme === 'dark' ? 'white' : 'black' }}>
This is a toolbar with {theme} theme
</div>
);
}
export default App;在上面的示例中,我们使用了 useContext hook 来获取父组件中传递下来的 context 值。这样可以方便地在子组件中访问到共享的数据。