如何使用 useContext 更改 Context 的值? [英] How to change the value of a Context with useContext?

查看:26
本文介绍了如何使用 useContext 更改 Context 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React 16.8+ 中使用 useContext 钩子效果很好.您可以创建组件、使用钩子并使用上下文值而不会出现任何问题.

我不确定的是如何将更改应用于 Context Provider 值.

1) useContext 钩子是否严格来说是一种使用上下文值的方法?

2) 是否有推荐的方法,使用 React 钩子来更新子组件的值,然后使用带有此上下文的 useContext 钩子触发任何组件的组件重新渲染?

const ThemeContext = React.createContext({风格:轻",可见:真实});功能内容(){const { 样式,可见 } = React.useContext(ThemeContext);const handleClick = () =>{//将上下文值更改为//样式:'暗'//可见:假}返回 (<div><p>主题是<em>{style}</em>和可见性状态是<em>{visible.toString()}</p><button onClick={handleClick}>更改主题</button>

)};功能应用(){返回<内容/>};const rootElement = document.getElementById('root');ReactDOM.render(, 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 FAQ 的一部分.

传递给 createContext 的参数只会是默认值,如果使用 useContext 的组件没有 Provider 在它上面进一步向上树.您可以改为创建一个 Provider 来提供 stylevisibility 以及切换它们的函数.

示例

const { createContext, useContext, useState } = React;const ThemeContext = createContext(null);功能内容(){const { 样式,可见,toggleStyle,toggleVisible } = useContext(主题上下文);返回 (<div><p>主题是<em>{style}</em>和可见性状态是<em>{visible.toString()}</p><button onClick={toggleStyle}>更改主题</button><button onClick={toggleVisible}>更改可见性</button>

);}功能应用(){const [style, setStyle] = useState("light");const [visible, setVisible] = useState(true);函数切换样式(){setStyle(style => (style === "light" ? "dark" : "light"));}功能切换可见(){setVisible(visible => !visible);}返回 (<ThemeContext.Provider值={{ 样式,可见,toggleStyle,toggleVisible }}><内容/></ThemeContext.Provider>);}ReactDOM.render(, document.getElementById("root"));

<script src="https://unpkg.com/react@16/umd/react.development.js"><;/脚本><script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><div id="root"></div>

Using the useContext hook with React 16.8+ works well. You can create a component, use the hook, and utilize the context values without any issues.

What I'm not certain about is how to apply changes to the Context Provider values.

1) Is the useContext hook strictly a means of consuming the context values?

2) Is there a recommended way, using React hooks, to update values from the child component, which will then trigger component re-rendering for any components using the useContext hook with this context?

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>

解决方案

How to update context with hooks is discussed in the How to avoid passing callbacks down? part of the Hooks FAQ.

The argument passed to createContext will only be the default value if the component that uses useContext has no Provider above it further up the tree. You could instead create a Provider that supplies the style and visibility as well as functions to toggle them.

Example

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 更改 Context 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆