【问题标题】:How to use custom theme in react navigation in class components如何在类组件的反应导航中使用自定义主题
【发布时间】:2020-05-14 10:23:52
【问题描述】:

我正在使用 react-navigation 5。我想知道如何在我的类组件中使用自定义主题定义的颜色(没有 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),以便它像使用效果挂钩一样动态变化,而不使用三元运算符并检查每一行的主题?

【问题讨论】:

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


    【解决方案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} />;
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      相关资源
      最近更新 更多