跳至主要內容
版本:6.x

主題

主題允許您變更 React 導覽提供的各種元件的顏色。您可以使用主題來

  • 自訂顏色,以符合您的品牌
  • 根據時間或使用者偏好提供淺色和深色主題

基本用法

若要傳遞自訂主題,您可以將 theme prop 傳遞至導覽容器。

import * as React from 'react';
import { NavigationContainer, DefaultTheme } from '@react-navigation/native';

const MyTheme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
primary: 'rgb(255, 45, 85)',
},
};

export default function App() {
return (
<NavigationContainer theme={MyTheme}>{/* content */}</NavigationContainer>
);
}

您可以動態變更主題 prop,所有元件都會自動更新,以反映新的主題。如果您尚未提供 theme prop,將會使用預設主題。

主題是包含可用顏色清單的 JS 物件。它包含下列屬性

  • dark (布林值):這是深色主題還是淺色主題
  • colors物件): react 導覽組件使用的各種顏色
    • primary字串): app 的主要顏色,用於為各種元素著色。通常您會想將您的品牌色用於此用途。
    • background字串):各種背景的顏色,例如螢幕的背景顏色。
    • card字串):類似卡片元素的背景顏色,例如標頭、分頁工具列等。
    • text字串):各種元素的文字顏色。
    • border字串):邊框的顏色,例如標頭邊框、分頁工具列邊框等。
    • notification字串):分頁導覽器的徽章顏色。

在建立自訂的主題時,您需要提供所有這些屬性。

主題範例

const MyTheme = {
dark: false,
colors: {
primary: 'rgb(255, 45, 85)',
background: 'rgb(242, 242, 242)',
card: 'rgb(255, 255, 255)',
text: 'rgb(28, 28, 30)',
border: 'rgb(199, 199, 204)',
notification: 'rgb(255, 69, 58)',
},
};

提供主題將負責所有官方導覽器的樣式。React 導覽器也提供一些工具,協助您自訂這些導覽器和其中的螢幕,這些螢幕也可以使用主題。

內建主題

由於作業系統都新增了內建的支援,來處理明暗模式,因此支援暗模式不再只是為了追趕潮流,而是要符合一般使用者對於應用程式運作方式的預期。為了以一種與作業系統預設值相當一致的方式來提供對明暗模式的支援,因而這些主題內建在 React 導覽器中。

您可以這樣匯入預設和深色主題

import { DefaultTheme, DarkTheme } from '@react-navigation/native';

使用作業系統偏好設定

在 iOS 13+ 和 Android 10+ 上,您可以藉由 (useColorScheme hook) 來取得使用者偏好的配色方案('dark''light')。

import { useColorScheme } from 'react-native';
import {
NavigationContainer,
DefaultTheme,
DarkTheme,
} from '@react-navigation/native';

export default () => {
const scheme = useColorScheme();

return (
<NavigationContainer theme={scheme === 'dark' ? DarkTheme : DefaultTheme}>
{/* content */}
</NavigationContainer>
);
};

在您自己的組件中使用目前的主題

若要在導覽器容器中呈現的任何組件中存取主題,您可以使用 useTheme hook。它會回傳主題物件

import * as React from 'react';
import { TouchableOpacity, Text } from 'react-native';
import { useTheme } from '@react-navigation/native';

// Black background and white text in light theme, inverted on dark theme
function MyButton() {
const { colors } = useTheme();

return (
<TouchableOpacity style={{ backgroundColor: colors.card }}>
<Text style={{ color: colors.text }}>Button!</Text>
</TouchableOpacity>
);
}