如何在使用useContext的React Hook时更改Context值
在useContextReact 16.8+上使用钩子效果很好。您可以创建一个组件,使用该钩子并利用上下文值,而不会出现任何问题。
我不确定的是如何将更改应用于Context Provider值。
1)useContext挂钩是否严格地是一种使用上下文值的方法?
2)是否有使用React钩子的推荐方法来更新子组件的值,然后该子组件将使用useContext此上下文的钩子触发任何组件的组件重新渲染?
const ThemeContext = React.createContext({  style: 'light',
  visible: true
});
function Content() {
  const { style, visible } = React.useContext(ThemeContext);
  const handleClick = () => {
    // change the context values to
    // style: 'dark'
    // visible: false
  }
  return (
    <div>
      <p>
        The theme is <em>{style}</em> and state of visibility is
        <em> {visible.toString()}</em>
      </p>
      <button onClick={handleClick}>Change Theme</button>
    </div>
  )
};
function App() {
  return <Content />
};
const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.2/umd/react-dom.production.min.js"></script>
回答:
在如何避免向下传递回调中讨论了如何使用钩子更新上下文。Hooks常见问题的一部分。
createContext仅当所使用的组件在树上useContext没有该组件时,传递给的参数才是默认值Provider。相反Provider,您可以创建一个提供style和visibility以及用于切换它们的功能的。
const { createContext, useContext, useState } = React;const ThemeContext = createContext(null);
function Content() {
  const { style, visible, toggleStyle, toggleVisible } = useContext(
    ThemeContext
  );
  return (
    <div>
      <p>
        The theme is <em>{style}</em> and state of visibility is
        <em> {visible.toString()}</em>
      </p>
      <button onClick={toggleStyle}>Change Theme</button>
      <button onClick={toggleVisible}>Change Visibility</button>
    </div>
  );
}
function App() {
  const [style, setStyle] = useState("light");
  const [visible, setVisible] = useState(true);
  function toggleStyle() {
    setStyle(style => (style === "light" ? "dark" : "light"));
  }
  function toggleVisible() {
    setVisible(visible => !visible);
  }
  return (
    <ThemeContext.Provider
      value={{ style, visible, toggleStyle, toggleVisible }}
    >
      <Content />
    </ThemeContext.Provider>
  );
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
以上是 如何在使用useContext的React Hook时更改Context值 的全部内容, 来源链接: utcz.com/qa/429081.html
