我试图从自定义挂钩中获取屏幕尺寸,但我不知道如何使用导入组件的结果。
显然,我可以使用{MyDims.Width}和{MyDims.Height}来显示结果,但对于我的最终脚本,我需要将这两个对象用作字符串,因此使用useState((。
这是导入的组件:getdimensions.js
import React, {
useState,
useEffect
} from "react";
import {
Dimensions
} from "react-native";
function App(props) {
const [Width, setWidth] = useState(0)
const [Height, setHeight] = useState(0)
const getDims = () => {
setWidth(Dimensions.get("screen").width)
setHeight(Dimensions.get("screen").height)
}
useEffect(() => {
getDims()
}, []);
return {Width, Height}
}
export default App;
主屏幕:App.js
import React, {
useState,
useEffect,
} from "react";
import { Text, View, StyleSheet } from 'react-native';
import useDimensions from './components/getdimensions';
export default function App() {
const MyDims = useDimensions()
const [ShowMyDims, setShowMyDims] = useState({
width: MyDims.Width,
height: MyDims.Height
})
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
width: {ShowMyDims.width} and
height: {ShowMyDims.height}
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: 50,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
您可以将其作为数组返回以避免其为object
。要从自定义挂钩获得组件useState
的更新,请添加useEffect
,并在自定义挂钩更改Width, Height
时触发状态更新。
// In your hook component
...
return [Width, Height];
// In main component
...
const [Width, Height] = useDimensions();
const [ShowMyDims, setShowMyDims] = useState({ width: Width, height: Height });
// Add a useEffect hook to listen the updates
useEffect(() => {
setShowMyDims({ width: Width, height: Height });
}, [Width, Height])
....
您可以选择从自定义挂钩直接使用Width, Height
到组件,而不需要中间useState
。