在 React Native 中访问主题颜色

Accessing Theme Color in React Native

我正在尝试访问主题的原色。我在执行此操作时遇到问题,因为错误显示“无法读取未定义的 属性 颜色”

请检查下面我的代码。

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

您从 react-native 导入 withTheme,它应该从 react-native-paper

导入

import {withTheme} from "react-native-paper"

你可以在react-native-paper

中这样使用它
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);

如果您已经定义了主题并想在此处导入它,那么您可以像下面这样使用 withTheme HOC

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

您可以创建一个名为 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);