React Context中的useContext解析及使用

上一篇:React Context上下文——初识

useContext

简单概括:useContext是读取context的值,以及订阅其变化的。
用法:

const MyContext = React.createContext();
const value = useContext(MyContext);

解释:
接收一个 context 对象(React.createContext 的返回值)并返回该 context 的当前值。
当前的 context 值由上层组件中距离当前组件最近的 Provider 的 props值决定。

const themes = {
  light: {
    foreground: "#000000",
    background: "yellow",
    font:'24px'
  },
  dark: {
    foreground: "#ffffff",
    background: "pink",
    font:'12px'
  }
};

const ThemeContext = React.createContext(themes.light);

// 第一层组件
function App() {
  return (
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

// 第二层组件
function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}
// 第三层子组件,useContext的使用点,重要!!! 
function ThemedButton() {
  // 这里直接使用 useContext,拿到 ThemeContext 的值 themes.light,效果是light的配置,背景色为黄色的那个
  const theme = useContext(ThemeContext);
  // 上句代码可以写为 const { foreground, background} = useContext(ThemeContext)
  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
      <span style={{ color: theme.foreground, fontSize: font }}> 我是测试的文字, 我是测试的啦</span>
    </button>
  );
}

效果如图:
React Context中的useContext解析及使用_第1张图片

参考:https://zh-hans.reactjs.org/docs/hooks-reference.html#usecontext

你可能感兴趣的:(前端,React,前端,reactjs,前端框架)