簡體   English   中英

react-native-elements 主題的聲明合並

[英]declaration merging for react-native-elements theme

我在我的 react-native 應用程序中使用 react-native-elements。

我的應用程序使用 ThemeProvider 進行包裝,以將主題傳遞給所有組件。

<SafeAreaProvider>
 <ThemeProvider theme={Theme}>
    <Loader visible={loader.loading} text={loader.message} absolute={true} />
    <RootNavigation />
  </ThemeProvider>
</SafeAreaProvider>

在主題文件中,我定義了我想在整個應用程序中使用的值。

const theme = {
  colors: {
    primary: '#6A69E2',
    primaryDark: '#4747c2',
    primaryLight: 'rgba(106, 105, 226, 0.35)',
    gray: {
      dark: '#242424',
      default: '#666',
      medium: '#999',
      light: '#ccc',
      lightest: '#e7e7e7',
    },
  },
  text: {
    size: {
      small: 12,
      default: 16,
      large: 18,
      h1: 26,
      h2: 22,
      h3: 20,
    },
  },
  Text: {
    style: {
      fontSize: 16,
      color: '#242424',
      fontFamily: 'Roboto',
    },
  },
  Button: {
    style: {
      borderRadius: 50,
    },
    disabledStyle: {
      backgroundColor: 'rgba(106, 105, 226, 0.35)',
    },
  },
};

export default theme;

對於值,提供此功能的 react-native-elements 的原始主題是有效的。 例如,我可以通過使用訪問 colors

const theme = useTheme()
theme.colors.primary

但是當我想添加一些新屬性時,比如primaryDark,我會得到一個linter 錯誤。

Object literal may only specify known properties, and 'primaryDark' does not exist in type 'RecursivePartial<Colors>'.ts(2322)

在 react-native-elements 的文檔中是關於聲明合並的一部分,但我不明白如何歸檔這個https://reactnativeelements.com/docs/customization/#typescript-definitions-extending-the-default-主題

有人可以幫我解決這個問題嗎?

好吧,聲明合並仍然有效。 這似乎是 lib 的一個錯誤。

他們的文檔說你可以在module 'react-native-elements'中增加Color接口。 但是目前(截至 2021 年 4 月 18 日,使用 v3.3.2)該接口實際上隱藏在module 'react-native-elements/dist/config/colors'內,而不是直接暴露在頂層,這很奇怪。

我建議你向他們的 repo 提出問題。 沒關系,有人已經提出了這個問題

在我的機器上測試,以下解決方案有效。

import React from 'react'
import { useTheme, ThemeProvider } from 'react-native-elements'

declare module 'react-native-elements/dist/config/colors' {
  export interface Colors {
    primaryDark: string
    primaryLight: string
  }
}

const ChildComp = () => {
  const theme = useTheme()
  theme.theme.colors.primaryDark // <-- No more error 🎉
  return <div>foobar</div>
}

回復 OP 的評論。 您可以隨心所欲地擴充界面,只要之前不存在擴充的鍵即可。 例如將foobar鍵添加到FullTheme

declare module 'react-native-elements' {
  export interface FullTheme {
    foobar: string
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM