useTheme
useTheme
Hook 允许我们访问当前激活的主题。你可以在你自己的组件中使用它,以便它们响应主题的变化。
- 静态
- 动态
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>
);
}
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>
);
}
有关如何配置主题的更多详细信息和使用指南,请参阅主题指南。
与类组件一起使用
你可以将你的类组件包裹在一个函数组件中来使用 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} />;
}