How to change Context value while using React Hook of useContext

前端 未结 2 576
情书的邮戳
情书的邮戳 2020-12-04 17:27

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

2条回答
  •  醉梦人生
    2020-12-04 17:52

    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 (
        

    The theme is {style} and state of visibility is {visible.toString()}

    ); } 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 ( ); } ReactDOM.render(, document.getElementById("root"));
    
    
    
    

提交回复
热议问题