我正在開發 React Native 應用程式,我的所有組件都是基于類的。現在我必須實作根據螢屏旋轉改變設計的螢屏旋轉功能。我正在嘗試使用useWindowDimensionsreact native 中的庫,但它會拋出無法從非功能組件呼叫掛鉤的錯誤。
誰能告訴如何在基于類的組件中使用鉤子,或任何其他方法來檢測螢屏尺寸以使螢屏回應螢屏旋轉?
uj5u.com熱心網友回復:
一個基本的功能組件如下所示:
const MyComponent = () => {
const { height, width } = useWindowDimensions();
return <>height: {height}, width: {width}</>;
}
您不能在基于類的組件中使用鉤子。
uj5u.com熱心網友回復:
嘗試:
import { Dimensions } from 'react-native';
// in your class component
componentDidMount() {
Dimensions.addEventListener("change", (handler) => this.setState({
wHeight: handler.window.height,
wWidth: handler.window.width
})
}
uj5u.com熱心網友回復:
嘿,您可以在基于類的組件中使用它來獲取視窗height和width
檢查這個
import {Dimensions} from 'react-native';
const screenWidth = Dimensions.get('window').width
const screenHeight = Dimensions.get('window').height
class ABC extends Comp {
render(){
const screenWidth = Dimensions.get('window').width
const screenHeight = Dimensions.get('window').height
return(
)
}
}
const styles = StyleSheet.create({
main:{
padding:screenWidth==25?20:30
}
})
希望對你有幫助,有疑問歡迎交流
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/503802.html
上一篇:根據輸入動態匯入React組件
