React Native - 使用来自自定义挂钩的对象

React Native - Using objects from Custom Hooks

我正在尝试从自定义挂钩获取屏幕尺寸,但我不知道如何使用导入组件的结果。

显然,我可以使用 {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',
  },
});

您可以 return 将它作为一个数组来避免它成为 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