我有一个在更改布局时检测窗口宽度和高度的功能。
检测宽度和高度的函数可以正常工作,但问题是在样式表文件中使用它们。
错误为:无效的钩子调用。钩子只能在函数组件的内部调用。
我的功能:
import { useEffect, useCallback, useState } from 'react';
import { Dimensions } from 'react-native';
export function useDimensions () {
const [windowWidth, setWindowWidth] = useState(Dimensions.get('window').width);
const [windowHeight, setWindowHeight] = useState(Dimensions.get('window').height);
useEffect(() => {
const callback = () => {
setWindowWidth(Dimensions.get('window').width);
setWindowHeight(Dimensions.get('window').height);
}
Dimensions.addEventListener('change', callback);
}, []);
return {windowWidth, windowHeight};
};
以下是我在样式表(自定义全局样式表文件(中尝试的内容:
import { StyleSheet } from "react-native";
import Colors from "./Colors";
import { windowHeight, windowWidth } from '../App/Components/Dimensions';
import { useDimensions } from '../App/Components/TestDimesions';
// Here is the problem : Invalid hook call...
const orientation = useDimensions();
const Global = StyleSheet.create({
test:{
width: windowWidht
}
});
export default Global
只能在react组件内部使用钩子。由于useDimensions
是一个钩子,您只能这样使用它:
function MyComponent() {
const orientation = useDimensions();
return (
<View style={[styles.test, { width: orientation.windowWidth }]} />
)
}
Use可以通过window.innerHeight和windows.innerWidth简单地获取高度和宽度。通过这两个可以获取窗口的高度和宽度。
除了必须在函数内部调用事实挂钩之外,use应该删除useEffect内部的eventlistener。
useEffect(() => {
//here
const listener = Dimensions.addEventListener('change', callback);
return () => listener.remove();
}, []);
您可以这样更新您的函数:
import { Dimensions } from 'react-native';
export const ScreenWidth = Dimensions.get('window').width;
export const ScreenHeight = Dimensions.get('window').height;
你可以通过导入使用它:
import { StyleSheet } from "react-native";
import Colors from "./Colors";
import { ScreenWidth, ScreenHeight } from '../App/Components/TestDimesions';
const Global = StyleSheet.create({
test:{
width: ScreenWidth,
}
});
export default Global