【问题标题】:React Context & Typescript with Custom Hook使用自定义 Hook 反应上下文和打字稿
【发布时间】:2021-06-29 11:54:51
【问题描述】:

我使用 React 和 Chakra-UI 创建了以下上下文提供程序:

import { useBoolean } from "@chakra-ui/react"
import { createContext } from "react"

const MobileContext = createContext<typeof useBoolean | undefined>(undefined)

function MobileProvider({ children }) {
  const [show, setShow] = useBoolean(false)

  return (
    <MobileContext.Provider value={{ show, setShow }}>
      {children}
    </MobileContext.Provider>
  )
}

不幸的是,上面的代码似乎不起作用。我在value={{ show, setShow }} 中的show 下得到一条红色波浪线,并带有以下消息:

Type '{ 
  show: boolean; 
  setShow: { 
    readonly on: () => void; 
    readonly off: () => void;  
    readonly toggle: () => void; 
  }; 
}' is not assignable to type 
  '(initialState?: InitialState) => 
  readonly [
      boolean, 
      { 
        readonly on: () => void; 
        readonly off: () => void; 
        readonly toggle: () => void; 
      }
   ]'.
  

Object literal may only specify known properties, and 'show' does not exist in type 

  '(initialState?: InitialState) => 
    readonly [
      boolean, 
      { 
        readonly on: () => void; 
        readonly off: () => void; 
        readonly toggle: () => void; 
      }
   ]'
   .ts(2322)
   index.d.ts(336, 9): 

The expected type comes from property 'value' which is declared here on type 
  'IntrinsicAttributes & ProviderProps<(initialState?: InitialState) => 
    readonly [
      boolean, 
      { 
         readonly on: () => void; 
         readonly off: () => void; 
         readonly toggle: () => void; 
      }
    ]
  >'

我想我明白问题所在——useBoolean 的返回值与showsetShow 不完全相同(尽管也许我错了)。无论哪种方式,我都无法弄清楚如何让它正常工作。

有什么想法吗?

谢谢。

【问题讨论】:

    标签: reactjs typescript react-context


    【解决方案1】:

    由于您提供了useBoolean返回值,并且您以不同的方式塑造上下文值,因此您应该 替换

    const MobileContext = createContext<typeof useBoolean | undefined>(undefined)
    
    

    type UseBooleanReturn = ReturnType<typeof useBoolean>
    
    const MobileContext = createContext<{show: UseBooleanReturn[0], setShow: UseBooleanReturn[1] } | undefined>(undefined)
    
    
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 2020-12-19
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 2019-04-19
      • 2023-03-08
      相关资源
      最近更新 更多