Skip to main content
Version: 7.x

useTheme

useTheme 钩子让我们可以访问当前活动的主题。你可以在自己的组件中使用它,让它们响应主题的更改。

¥The useTheme hook lets us access the currently active theme. You can use it in your own components to have them respond to changes in the theme.

import { useTheme } from '@react-navigation/native';

function MyButton() {
const { colors } = useTheme();

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

有关如何配置主题的更多详细信息和使用指南,请参阅 主题指南

¥See theming guide for more details and usage guide around how to configure themes.

与类组件一起使用

¥Using with class component

你可以将类组件封装在函数组件中以使用钩子:

¥You can wrap your class component in a function component to use the hook:

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