React native navigation useTheme()(反应原生导航 useTheme())
问题描述
我正在尝试直接从样式中访问 useTheme()但到目前为止,我的解决方案似乎不起作用.我不会出错.有没有办法做我想做的事?
I'm trying to access useTheme() directly from the styles But so far my solution doesn't seem to work. I'm not getting in error back. Is there a way to do what I'm trying to do?
import { StyleSheet } from "react-native";
import { useTheme } from '@react-navigation/native'
export default function () {
const { colors } = useTheme();
const styles = GlobalStyles({ colors: colors })
return styles
}
const GlobalStyles = (props) => StyleSheet.create({
container: {
flex: 1,
backgroundColor: props.colors.backgroundColor,
},
})
在组件中访问样式
import React from "react";
import GlobalStyles from "../globalStyles.js"
class Inventory extends React.Component {
render() {
return (
<View style={globalStyles.container}>
)
}
推荐答案
你有几个问题:你只能在钩子或函数组件中使用钩子.所以你可以将你的全局样式表转换成一个钩子:
You have a couple of issues: you can only use a hook within a hook or a function component. So you could convert your global stylesheet into a hook:
import { StyleSheet } from "react-native";
import { useTheme } from '@react-navigation/native'
const getGlobalStyles = (props) => StyleSheet.create({
container: {
flex: 1,
backgroundColor: props.colors.backgroundColor,
},
});
function useGlobalStyles() {
const { colors } = useTheme();
// We only want to recompute the stylesheet on changes in color.
const styles = React.useMemo(() => getGlobalStyles({ colors }), [colors]);
return styles;
}
export default useGlobalStyles;
然后,您可以通过将 Inventory
类组件转换为函数组件并使用新的 useGlobalStyles
挂钩来使用该挂钩.
Then you can use the hook by converting your Inventory
class component into a function component and using the new useGlobalStyles
hook.
import React from "react";
import useGlobalStyles from "../globalStyles.js"
const Inventory = () => {
const globalStyles = useGlobalStyles();
return (
<View style={globalStyles.container}>
)
}
这篇关于反应原生导航 useTheme()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:反应原生导航 useTheme()


- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01