简体   繁体   中英

React prop types for custom hook

I have a component that returns an object (color theme object), which has nested objects for certain 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:

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. 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 . Both WebStorm or Visual Studio Code can understand type annotations and they subsequently provide suggestions.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM