我有一個功能可以在更改布局時檢測視窗的寬度和高度。
檢測寬度和高度的功能作業正常,但問題是在樣式表檔案上使用它們。
錯誤是:無效的掛鉤呼叫。Hooks 只能在函陣列件的主體內部呼叫。
我的功能:
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
uj5u.com熱心網友回復:
您只能在反應組件內部使用鉤子。因為useDimensions是一個鉤子,你只能像這樣使用它:
function MyComponent() {
const orientation = useDimensions();
return (
<View style={[styles.test, { width: orientation.windowWidth }]} />
)
}
uj5u.com熱心網友回復:
使用可以簡單地通過window.innerHeight和window.innerWidth獲得高度和寬度。通過這兩個,您可以獲得視窗的高度和寬度。
uj5u.com熱心網友回復:
除了必須在函式內部呼叫的事實掛鉤之外,使用應該洗掉 useEffect 內部的事件監聽器。
useEffect(() => {
//here
const listener = Dimensions.addEventListener('change', callback);
return () => listener.remove();
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/526790.html
上一篇:R組合和創建功能
