问题描述
我正在尝试从自定义钩子获取屏幕尺寸,但我不知道如何使用导入组件的结果。
很明显,我可以使用{MyDims.Width}和{MyDims.Height}来显示结果,但是对于我的最终脚本,我需要将2个对象用作字符串,因此使用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,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
。