如何在类组件的React导航中使用自定义主题

时间:2020-05-14 10:23:52

标签: react-native react-navigation react-navigation-v5

我正在使用react-navigation5。我想知道如何在类组件中使用自定义主题定义的颜色(不使用useTheme)。以便在主题更改时动态更改。

这是我的自定义主题。

const DarkTheme = {
    dark: true,
    colors: {
        primary: colors.green,
        background: colors.black85,
        card: colors.black25,
        text: colors.white,
        border: colors.white,
    },
};

这是我的导航器

<NavigationContainer
    ref={navigationRef}
    theme={theme === THEMES.DARK ? DarkTheme : LightTheme}>
    {authenticated ? (
        <DrawerNavigator />
    ) : (
            <AuthStackNavigator {...this.props} />
        )}
</NavigationContainer>

那么我该如何在类组件中使用这些主题颜色键(colors.primary),使其像使用效果钩子一样动态变化,而无需使用三元运算符并在每一行上检查主题?

1 个答案:

答案 0 :(得分:1)

根据文档,您可以将类组件包装在函数组件中以使用钩子:

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