zoukankan      html  css  js  c++  java
  • reactjs —— useContext :上下文 & 属性之间的传递 & 全局变量

    原文:

    https://www.react.express/hooks/usecontext

    useContext

    We use the useContext hook for passing values to deeply nested components. This is essentially dependency injection.

    We frequently use contexts for values which will be used throughout our app, such as theme constants or localized strings.

    Example

    Suppose we want to use a theme throughout our app.

    Without contexts

    Without a context, we have to pass the theme as a prop into every component - even those that don't use it! That's both a hassle and may cause unnecessary rerendering.

    import React, { useContext } from 'react'
    
    function Title({ theme }) {
      const style = {
        background: theme.primary,
        color: theme.text,
      }
    
      return <h1 style={style}>Title</h1>
    }
    
    function Nested({ theme }) {
      return <Title theme={theme} />
    }
    
    function NestedTwice({ theme }) {
      return <Nested theme={theme} />
    }
    
    export default function App() {
      const theme = {
        primary: 'dodgerblue',
        text: 'white',
      }
    
      return <NestedTwice theme={theme} />
    }
    

      

    With contexts

    With a context, the component that actually wants to use the theme can access it directly from the context.

    import React, { useContext, createContext } from 'react'
    
    const ThemeContext = React.createContext()
    
    function Title() {
      const theme = useContext(ThemeContext)
    
      const style = {
        background: theme.primary,
        color: theme.text,
      }
    
      return <h1 style={style}>Title</h1>
    }
    
    function Nested() {
      return <Title />
    }
    
    function NestedTwice() {
      return <Nested />
    }
    
    export default function App() {
      const theme = {
        primary: 'dodgerblue',
        text: 'white',
      }
    
      return (
        <ThemeContext.Provider value={theme}>
          <NestedTwice />
        </ThemeContext.Provider>
      )
    }
    

      

     

     

  • 相关阅读:
    第04组 Beta冲刺(2/5)
    第04组 Beta冲刺(1/5)
    第04组 Alpha事后诸葛亮
    第04组 Alpha冲刺(6/6)
    第04组 Alpha冲刺(5/6)
    第04组 Alpha冲刺(4/6)
    第04组 Alpha冲刺(3/6)
    作业2-1:矩阵协方差
    作业lab1-1:lammps教程总结
    如何在服务器上传/下载文件
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/15267641.html
Copyright © 2011-2022 走看看