如何在样式表创建中使用 useTheme 挂钩?

问题描述 投票:0回答:3

我想在组件内的样式表创建函数中使用我的 React Native Paper 主题中的颜色。这是我的代码

import { StyleSheet, Text, View } from 'react-native';
import { useTheme } from 'react-native-paper';

const Home = () => {
  const { colors } = useTheme();

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <Text>Home Page</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});


export default Home;

我想在样式表中使用backgroundColor: "#fff"来引用来自useTheme钩子的colors.background。这可能吗?

react-native themes react-native-paper
3个回答
28
投票

我更喜欢这样使用

const makeStyles = (colors: any) => StyleSheet.create({
   container: {
       backgroundColor: colors.red,
   }
})

然后,在 render() 中

  const Home = () => {
  const { colors } = useTheme();
  const styles = makeStyles(colors)
  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <Text>Home Page</Text>
    </View>
  );
}

1
投票

https://stackoverflow.com/a/65259425/8142053

我最近从 StackOverflow 找到了这个答案,根据该答案,您可以编写一个 customHook 并在自定义钩子中使用它。请查看他的回答以获得清晰的理解。


0
投票
import {Theme, useTheme} from '@react-navigation/native';
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';

function HomeScreen(): React.JSX.Element {
  const theme = useTheme();
  const styles = makeStyles(theme);

  return (
    <View style={styles.container}>
      <Text>Home</Text>
    </View>
  );
}

const makeStyles = ({colors}: Theme) =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background,
      alignItems: 'center',
      justifyContent: 'center',
    },
  });

export default HomeScreen;

这应该适用于 tsx

© www.soinside.com 2019 - 2024. All rights reserved.