【问题标题】:React native navigation useTheme()反应原生导航 useTheme()
【发布时间】:2021-03-23 06:28:52
【问题描述】:

我正在尝试直接从样式中访问 useTheme() 但到目前为止,我的解决方案似乎不起作用。 我不会出错。 有没有办法做我想做的事?

 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}>
            )
    
     }

【问题讨论】:

    标签: javascript reactjs react-native expo stylesheet


    【解决方案1】:

    你有几个问题:你只能在钩子或函数组件中使用钩子。所以你可以将你的全局样式表转换成一个钩子:

    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 挂钩来使用挂钩。

    import React from "react";
    import useGlobalStyles from "../globalStyles.js"
        
    const Inventory = () => {
      const globalStyles = useGlobalStyles();
    
      return (
        <View style={globalStyles.container}>
      )
    }
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 2017-06-09
    • 2020-11-26
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多