在React Native中访问主题颜色

35g0bw71  于 2022-12-24  发布在  React
关注(0)|答案(4)|浏览(145)

我正在尝试访问主题的原色。我遇到了问题,因为错误显示“无法读取未定义的属性颜色”
请检查我下面的代码。

import React, { memo } from "react";
import { StyleSheet, Text, withTheme } from "react-native";

const Header = ({ children }) => <Text style={styles.header}>{children}</Text>;

const styles = StyleSheet.create({
  header: {
    fontSize: 26,
    color: withTheme.colors.primary,
  },
});

export default memo(Header);
deikduxw

deikduxw1#

您可以创建一个名为useStyles的函数,然后通过参数传递主题对象。
示例:

import React, { memo } from "react";
import { StyleSheet, Text } from "react-native";
import { useTheme } from 'react-native-paper'; //or styled-components theme object 

const Header = ({ children }) => {

  const theme = useTheme();
  const styles = useStyles(theme);

  return <Text style={styles.header}>{children}</Text>;
}


const useStyles = theme => (StyleSheet.create(({
  container: {
    ...
  },
  header: {
    fontSize: 26,
    color: theme.colors.primary,
  },
  something: {
    ...
    backgroudColor: theme.colors.background,
  },
  other: {
    ...
    color: theme.colors.primary,
  },
)))

export default memo(Header);
ffscu2ro

ffscu2ro2#

你可以像这样用在React纸上

import React, { memo } from "react";
import { StyleSheet, Text } from "react-native";
import { DefaultTheme } from 'react-native-paper';

const theme =  ({
    ...DefaultTheme,
    colors: {
        ...DefaultTheme.colors,
    }
});
const Header = ({ children }) => <Text style={styles.header}>{children}</Text>;

const styles = StyleSheet.create({
  header: {
    fontSize: 26,
    color: theme.colors.primary,
  },
});

export default memo(Header);

如果你已经定义了一个主题,并且想在这里导入它,那么你可以像下面这样使用withThemeHOC

import React, { memo } from "react";
import { StyleSheet, Text } from "react-native";
import { withTheme } from 'react-native-paper';

const Header = ({ theme, children }) => {
    const styles = StyleSheet.create({
        header: {
            fontSize: 26,
            color: theme.colors.primary,
        },
    });
    return (
        <Text style={styles.header}>{children}</Text>
    )
}

export default memo(withTheme(Header));
t9eec4r0

t9eec4r03#

您从react-native导入withTheme,它应该从react-native-paper导入
import {withTheme} from "react-native-paper"

o7jaxewo

o7jaxewo4#

你可以这样写一个钩子生成器

import { useTheme } from "@react-navigation/native"
import { useMemo } from "react";
import { StyleSheet } from "react-native";

export const makeStyles = (styles) => (props) => {
  const theme = useTheme();

  return useMemo(() => {
    const css = typeof styles === 'function' ? styles(theme, props) : styles;
    return StyleSheet.create(css);
  }, [props, theme]);

};

然后像这样使用它

const ListScreen = () => {
  const styles = useStyles();

  return (
    <View>
      <Text style={styles.text}>ListScreen</Text>
    </View>
  );
};

export default ListScreen;

const useStyles = makeStyles((theme, props) => ({
  text: {
    color: theme.colors.primary,
  },
}));

相关问题