简体   繁体   English

自定义钩子的 React 道具类型

[英]React prop types for custom hook

I have a component that returns an object (color theme object), which has nested objects for certain styles.我有一个返回 object(颜色主题对象)的组件,它具有某些 styles 的嵌套对象。

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

This colorPalette object is stored inside a context, which is accessed, by doing this:这个 colorPalette object 存储在上下文中,可以通过以下方式访问:

context.providerValue.colorPalette

So, since I am using the colorPalette a lot, it does not make sense for me to use a color by accessing the colorPalette this way so I created a custom hook.因此,由于我经常使用 colorPalette,因此通过这种方式访问 colorPalette 来使用颜色对我来说没有意义,因此我创建了一个自定义挂钩。 Looks like this:看起来像这样:

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

usage looks like this:用法看起来像这样:

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

What I'm trying to do is for the available values to appear when I do我正在尝试做的是在我这样做时出现可用值

colors.
or colors.bg.

So the available options appear, but not sure how to do it considering this is not a component...所以出现了可用的选项,但考虑到这不是一个组件,不确定如何去做......

If you just need autocompletion of the IDE, you could use JSDoc type annotations .如果您只需要自动完成 IDE,您可以使用JSDoc 类型注释 Both WebStorm or Visual Studio Code can understand type annotations and they subsequently provide suggestions. 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