How to update React Context from inside a child component?

前端 未结 3 1955
醉梦人生
醉梦人生 2020-11-30 19:10

I have the language settings in the context as like below

class LanguageProvider extends Component {
  static childContextTypes = {
    langConfig: PropType         


        
3条回答
  •  既然无缘
    2020-11-30 19:22

    The Above answer by Maithani is a great solution but that is a class component without the use of hooks. Since it is recommended by React to use functional components and hooks so I will implement it with useContext and useState hooks. Here is how you can update the context from within a child component.

    LanguageContextMangement.js

    import React, { useState } from 'react'
    
    export const LanguageContext = React.createContext({
      language: "en",
      setLanguage: () => {}
    })
    
    export const LanguageContextProvider = (props) => {
    
      const setLanguage = (language) => {
        setState({...state, language: language})
      }
    
      const initState = {
        language: "en",
        setLanguage: setLanguage
      } 
    
      const [state, setState] = useState(initState)
    
      return (
        
          {props.children}
        
      )
    }
    

    App.js

    import React, { useContext } from 'react'
    import { LanguageContextProvider, LanguageContext } from './LanguageContextManagement'
    
    function App() {
    
      const state = useContext(LanguageContext)
    
      return (
        
          
        
      )
    }
    
    export default App
    

提交回复
热议问题