【发布时间】:2021-12-30 10:45:56
【问题描述】:
根据一些谷歌搜索,我尝试了 2 种不同的方法来做到这一点。 我正在尝试为 typescript expo 反应式原生项目 中的自定义主题设置类型。 我已经设置了一个声明 ts 文件并将其添加到我的 tsconfig 中。这是我的设置。希望有人遇到过类似的问题并且知道如何解决这个问题。
我有一个主题文件夹,其中包含以下文件,我将其导出然后导入索引主题文件。
themes/
colors
sizes
spacing
index
这里是从上述主题文件中导入的索引文件。
import { DefaultTheme } from "styled-components/native";
import { colors } from "./colors";
import { sizes } from "./sizes";
import { spacing, lineHeights } from "./spacing";
const theme: DefaultTheme = {
colors,
sizes,
spacing,
lineHeights,
};
export default theme;
然后我有我的声明文件,我尝试了两种方法,一种是手动添加所有道具,另一种是使用 typeof。
types/theme.d.ts
import {} from "styled-components";
import theme from "../themes";
declare module "styled-components" {
type Theme = typeof theme;
export interface DefaultTheme extends Theme {}
}
// Manually adding the props.
// import { DefaultTheme } from "styled-components/native";
// declare module "styled-components" {
// export interface DefaultTheme {
// bg: {
// primary: string;
// secondary: string;
// };
// sizes: stringp[];
// lineHeights: {
// title: string;
// copy: string;
// };
// spacing: string[];
// }
// }
tsconfig.json
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true,
"baseUrl": ".",
"paths": {
"*": ["types/*"]
},
},
"include": ["./src", "./types"],
"exclude": [
"node_modules",
"**/*.test.ts",
"**/*.test.tsx",
]
}
这就是我在我的 tsx 应用程序文件中使用它的方式。
App.tsx
import React from "react";
import styled, { ThemeProvider } from "styled-components/native";
import { Text, StatusBar } from "react-native";
import theme from "./src/themes";
export default function App() {
return (
<ThemeProvider theme={theme}>
<Container>
<Text>some text</Text>
<StatusBar />
</Container>
</ThemeProvider>
);
}
const Container = styled.View`
flex: 1;
background-color: ${({ theme }) => theme.colors.bg.primary};
align-items: center;
justify-content: center;
`;
【问题讨论】:
-
我看不出这种方法有什么问题,但我对此
declare module "styled-components"有疑问,您正在从styled-components/native导入DefaultTheme。也许您应该在declare module中使用该路径(顺便说一句,我在网络应用程序中使用了相同的方法并且它有效) -
感谢 Diego,我将 DefaultTheme 导入 types/theme.d.ts 并更改了“../src/themes”的路径;这是不正确的。但这仍然不能解决问题。例如行 background-color: ${({ theme }) => theme.colors.bg.primary};我对颜色感到警惕,它说“默认主题不存在颜色”
标签: typescript react-native expo typescript-typings styled-components