#typescript #react-native #expo #typescript-typings #styled-components
Вопрос:
Я попробовал 2 разных способа сделать это, основываясь на некоторых результатах поиска в Google. Я пытаюсь настроить ввод текста для пользовательской темы в собственном проекте 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;
затем у меня есть файл декларации, который я попробовал 2 способами: один вручную, добавив все реквизиты, а другой с помощью typeof.
типы/тема.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.
Приложение.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 ( lt;ThemeProvider theme={theme}gt; lt;Containergt; lt;Textgt;some textlt;/Textgt; lt;StatusBar /gt; lt;/Containergt; lt;/ThemeProvidergt; ); } const Container = styled.View` flex: 1; background-color: ${({ theme }) =gt; theme.colors.bg.primary}; align-items: center; justify-content: center; `;
Комментарии:
1. Я не вижу ничего плохого в этом подходе, но я сомневаюсь в том
declare module "styled-components"
, что вы импортируетеDefaultTheme
изstyled-components/native
. Возможно, вам следует использовать этот путь вdeclare module
(кстати, я использую тот же подход в веб-приложении, и он работает).2. Спасибо Диего, я импортировал DefaultTheme в types/theme.d.ts, а также изменил путь для «../src/темы»; что неверно. Но это все равно ничего не исправляет. Например, цвет фона строки: ${({ тема }) =gt; theme.colors.bg.primary}; Я получаю предупреждение о цветах, в котором говорится: «цвета не существуют в теме по умолчанию «»
Ответ №1:
Не садись DefaultTheme
в свое themes/index.ts
. Он уже используется и является просто пустым объектом.
Обновите свой themes/index.ts
до этого:
import { colors } from "./colors"; import { sizes } from "./sizes"; import { spacing, lineHeights } from "./spacing"; const theme = { colors, sizes, spacing, lineHeights, }; export default theme;
Обновите свой types/theme.d.ts
этот:
import "styled-components" import theme from "./src/themes"; type ThemeInterface = typeof theme declare module "styled-components" { // eslint-disable-next-line @typescript-eslint/no-empty-interface (this is only necessary if you ur eslint complains. Since it should be and Interface and not a Type.) interface DefaultTheme extends ThemeInterface {} }
И ты должен быть гуччи.