iT邦幫忙

2021 iThome 鐵人賽

DAY 12
0
Modern Web

30天學 React.js 系列 第 12

[Day12] [筆記]React Hooks - UseContent

前言

介紹 useContext 前,我們必須先認識 Context

Context 概念有點像是 React 的全域變數概念,像是使用者登入狀態樣式等等。

useContext

根據官方文件寫道,它會接受一個 context object(React.createContext 的回傳值)並回傳該 context 目前的值。

context object

  1. Provider:傳遞 value 值
  2. Consumer:接受 value 值
const value = useContext();
const { Provider, Consumer } = value ; 

官網範例

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

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

function App() {
  return (
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

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

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

使用時機和注意事項

  • 因為 context 每當它資料更新時,底下所有子元件都會重新 re-render,所以他比較適合一些固定資料,如登入者資訊。
  • useContext 的參數必需為 context object 自己
    • 正確: useContext(MyContext)

參考資料


上一篇
[Day11] [筆記]React Hooks - UseRef
下一篇
[Day13] [筆記]React Hooks-UseReducer
系列文
30天學 React.js 14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言