首页 > 解决方案 > 如何在 React Native 的类组件中调用钩子?

问题描述

使用的技术

React Native Appearance、Typescript 和 Redux 重新匹配。

问题

我正在尝试将自定义主题颜色传递给类组件。我也明白钩子不能在类组件中使用/调用,只能在功能组件中使用。我之所以使用类组件是因为 Redux Rematch。有没有办法让我从下面列出的钩子中获取我的颜色到我的类组件中?

这就是我构建主题的方式:

索引.tsx

const palette = {
 colourTextDark: "#ffffff",
 colourTextLight: "#000000",
};

export const colors = {
  colourText: palette.colourTextLight,
};

export const themedColors = {
  default: {
    ...colors,
  },
  light: {
    ...colors,
  },
  dark: {
    ...colors,
    colourText: palette.colourTextDark,
  },
};

钩子.tsx

import { useColorScheme } from "react-native-appearance";
import { themedColors } from "./";

export const useTheme = () => {
  const theme = useColorScheme();
  const colors = theme ? themedColors[theme] : themedColors.default;
  return {
    colors,
    theme,
  };
};

理想情况下,我想像这样使用它:

import { useTheme } from "../../theme/hooks";

...

class Example extends React.Component<Props> {
  render() {
     // This doesn't work
     const { colors } = useTheme();

     return (
        <Text style={{ color: colors.colourText }}>Please help :)</Text>
     )
  }
}

我怎么能做到这一点?提前致谢 :)

标签: react-nativereduxreact-reduxthemes

解决方案


您可以像这样创建一个高阶组件:

const themeHOC = (Component) => {
  return (WrappedComponent = (props) => {
    const { colors } = useTheme();

    return <Component {...props} colors={colors} />;
  });
};

并像这样使用它:

themeHOC(<Example />)

推荐阅读