Skip to main content

谈谈 useContent

是什么

  1. useContext(MyContext) 相当于 class 组件中的 <MyContext.Consumer>
  2. useContext(MyContext) 只是让你能够读取 context 的值以及监听 context 的变化。仍然需要在上层组件树中使用 <MyContext.Provider> 来为下层组件提供 context。

怎么用

预览地址

import React, { createContext, useContext, useState } from "react";

const themes = {
light: {
foreground: "#000000",
background: "#eeeeee"
},
dark: {
foreground: "#ffffff",
background: "#222222"
}
};

const ThemeContext = createContext(themes.light);

function App() {
const [color, setColor] = useState(themes.dark);

const onColor = () => {
setColor(themes.light);
};

return (
<ThemeContext.Provider value={{ color, onColor }}>
<Toolbar />
</ThemeContext.Provider>
);
}

function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}

function ThemedButton() {
const { color, onColor } = useContext(ThemeContext);
return (
<button
onClick={onColor}
style={{ background: color.background, color: color.foreground }}
>
I am styled by theme context!
</button>
);
}

export default App;