簡體   English   中英

自定義鈎子的 React 道具類型

[英]React prop types for custom hook

我有一個返回 object(顏色主題對象)的組件,它具有某些 styles 的嵌套對象。

let colorPalette = {
 bgColors: {
  main: 'red',
  default: 'pink',
  ...
 },
 textColors: {
  main: 'black',
  default: 'red',
  ...
 }  
}

這個 colorPalette object 存儲在上下文中,可以通過以下方式訪問:

context.providerValue.colorPalette

因此,由於我經常使用 colorPalette,因此通過這種方式訪問 colorPalette 來使用顏色對我來說沒有意義,因此我創建了一個自定義掛鈎。 看起來像這樣:

const useGetColors = () => {
  let context = useContext(CustomContext)
   return context.providerValue.color
}

用法看起來像這樣:

let colors  = useGetColors()
backgroundColor: colors.bg.main

我正在嘗試做的是在我這樣做時出現可用值

colors.
or colors.bg.

所以出現了可用的選項,但考慮到這不是一個組件,不確定如何去做......

如果您只需要自動完成 IDE,您可以使用JSDoc 類型注釋 WebStorm 或 Visual Studio Code 都可以理解類型注釋,並隨后提供建議。

/**
 * @typedef {{
 *   bg: {
 *    main: string;
 *    default: string;
 *   },
 *   text: {
 *    main: string;
 *    default: string;
 *   }
 * }} ColorTheme
 * 
 * Returns colors theme
 * @returns {ColorTheme}
 */
function useGetColors() {
 ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM