使用自定义钩子响应上下文和打字稿

时间:2021-06-29 11:54:51

标签: reactjs typescript react-context

我使用 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>
  )
}

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

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 不完全相同(尽管我可能错了)。无论哪种方式,我都无法弄清楚如何让它正常工作。

有什么想法吗?

谢谢。

1 个答案:

答案 0 :(得分: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)