react-native - 如何在 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>
)
}
}
我怎么能做到这一点?提前致谢 :)
解决方案
您可以像这样创建一个高阶组件:
const themeHOC = (Component) => {
return (WrappedComponent = (props) => {
const { colors } = useTheme();
return <Component {...props} colors={colors} />;
});
};
并像这样使用它:
themeHOC(<Example />)
推荐阅读
- nginx - nginx 从不同的位置指令发送标头
- tensorflow - 训练图像?选择注意事项
- python - 这种 python 索引:'print(X_train[y_train == 0][0])' 如何在 python 中工作?
- php - 使用未定义的常量标题 - 假定为“标题”
- docker - 如何从 hyper-v 虚拟机连接到 windows docker 容器的公开端口?
- python - 节点错误在远程服务器上生成 /bin/sh ENOENT
- javascript - 在spring mvc视图上实现UI-GRID angular
- django - 如何对 Django FloatField/DecimalField 进行比较操作
- javascript - Javascript查找两个数组缺失元素的索引
- google-chrome - Chrome 和 HTML5 离线存储