如何在Typescript中的Context中使用React Hooks



我在新的react原生项目中使用以下代码,以使用TailwindCSS:支持黑暗模式

import React, { createContext, useState, useContext } from 'react';
import { Appearance } from 'react-native';
import { create } from 'tailwind-rn';
import styles from '../styles.json';
const { tailwind, getColor } = create(styles);
export default tailwind;
export { getColor };
const TailwindContext = createContext({});
const handleThemeClasses = (classes: string, isDarkMode: Boolean) => {
const regExp = isDarkMode ? /dark:/g : /dark:S+/g;
return classes.replace(regExp, "").replace(/ss/g, " ").trim();
}
const useTailwind = () => {
const context = useContext(TailwindContext);
if (!context) throw new Error(`useTailwind must be used within a TailwindProvider`);
const [currentColorScheme, setCurrentColorScheme] = context;
const isDarkMode = currentColorScheme == "dark";
return {
isDarkMode,
setDarkMode: (isDark: Boolean) => setCurrentColorScheme(isDark ? "dark" : "light"),
tw: (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode)),
getColor: (colors: string) => getColor(handleThemeClasses(colors, isDarkMode)),
};
}
const TailwindProvider: React.FC<{}> = ({ children }) => {
const contextValue = useState(Appearance.getColorScheme());
return <TailwindContext.Provider value={contextValue}>{children}</TailwindContext.Provider>;
}
export { TailwindProvider, useTailwind }

但是我得到了一个Typescript错误的代码行:

const [currentColorScheme, setCurrentColorScheme] = context; //Type '{}' is not an array type.

我需要如何配置我的createContext才能在Typescript中工作,有什么想法吗?

我不使用typescript,但我通常是这样做的。

const useTailwind = () => {
const context = useContext(TailwindContext);
if (!context) throw new Error(`useTailwind must be used within a TailwindProvider`);
//do all the deleted stuff in the Provider because you are suppose to return context here.
return context
}

提供商

const [ color, setColor ]  = useState(Appearance.getColorScheme());
//do whatever u need here, and return the value below
const customFunction = () => 'Hello'
return <TailwindContext.Provider value={{ color, setColor, customFunction }}>{children}</TailwindContext.Provider>;

然后我用我的钩子作为

const { color, setColor, customFunction } = useTailwind()

记得用TailwindProvider 包装应用程序

上下文的Typescript示例

export type MyContent = {
copy: string
setColor:(c: string) => void
}
export const MyContext = createContext<MyContent>({
copy: 'dark', // set a default value
setColor: () => {},
})
React的createContext是用描述上下文值的泛型类型参数T定义的。当你做
const TailwindContext = createContext({});

TS推断您的上下文具有类型{}。这与明确地将其写为:相同

const TailwindContext = createContext<{}>({});

您应该显式指定类型参数。这样做需要提供一个与指定类型匹配的defaultValue,但通常可以使用as进行断言,因为不应该使用默认值(只要您在组件树的更高位置正确地安装了上下文提供程序(。

export interface TailwindContextType {
color: string;
setColor: (color: string) => void;
customFunction: () => void;
}
const TailwindContext = createContext<TailwindContextType>({} as TailwindContextType);

你会这样使用它:

const useTailwind = () => {
const context = useContext(TailwindContext);

// use `null` as the default value when calling `createContext`
// if you want to include a check like this; if you use `{}`,
// `context` will be `{}` and this check won't catch it
// if (!context) throw new Error('...');
const { color, setColor } = context;
const isDarkMode = color == 'dark';
return {
isDarkMode,
setDarkMode: (isDark: boolean) => setColor(isDark ? 'dark' : 'light'),
// ...
};
};
const MyComponent = () => {
const { isDarkMode, setDarkMode } = useTailwind();
// ...
};

您可以在此处阅读有关泛型类型的更多信息。

最新更新