【问题标题】:How do I use the useTheme hook inside my Stylesheet create?如何在我的样式表创建中使用 useTheme 挂钩?
【发布时间】:2021-03-30 02:38:09
【问题描述】:

我想在我的组件内的样式表创建函数中使用我的 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。这可能吗?

【问题讨论】:

  • 您可以在 Home 功能/组件中使用样式表

标签: react-native themes react-native-paper


【解决方案1】:

我更喜欢这样使用它

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-10-23
      • 2019-09-02
      • 2020-08-22
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多