How to change Context value while using React Hook of useContext

前端 未结 2 604
情书的邮戳
情书的邮戳 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 18:11

    You can use this approach, no matter how many nested components do you have it will work fine.

    // Settings Context - src/context/Settings
    import React, { useState } from "react";
    
    const SettingsContext = React.createContext();
    
    const defaultSettings = {
       theme: "light",
    };
    
    export const SettingsProvider = ({ children, settings }) => {
       const [currentSettings, setCurrentSettings] = useState(
          settings || defaultSettings
       );
    
       const saveSettings = (values) => {
         setCurrentSettings(values)
       };
    
       return (
          
             {children}
          
       );
    };
    
    export const SettingsConsumer = SettingsContext.Consumer;
    
    export default SettingsContext;
    
    // Settings Hook - src/hooks/useSettings
    import { useContext } from "react";
    import SettingsContext from "src/context/SettingsContext";
    
    export default () => {
       const context = useContext(SettingsContext);
    
       return context;
    };
    
    // src/index
    ReactDOM.render(
       
             
       ,
       document.getElementById("root")
    
    // Any component do you want to toggle the theme from
    // Example: src/components/Navbar
    const { settings, saveSettings } = useSettings();
    
    const handleToggleTheme = () => {
      saveSettings({theme: "light"});
    };
    

提交回复
热议问题