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

useTheme

useTheme 掛勾讓我們可以使用目前啟用的佈景主題。您可以在自己的元件中使用此掛勾,讓這些元件對佈景主題變更做出回應。

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>
);
}

請參閱佈景主題指南,其中提供更詳細的說明和使用指南,瞭解如何設定佈景主題。

與類別元件一起使用

您可以將類別元件封裝在一個函式元件中,以使用這個掛勾。

class MyButton extends React.Component {
render() {
// Get it from props
const { theme } = this.props;
}
}

// Wrap and export
export default function (props) {
const theme = useTheme();

return <MyButton {...props} theme={theme} />;
}