import {useEffect, useState} from "react"; import {Image, ImageSourcePropType} from "react-native"; import {ImageURISource} from "react-native/Libraries/Image/ImageSource"; const useData = (source: ImageSourcePropType, width?: number, height?: number, setHeight?: any) => { // 比例 const [ratio, setRatio] = useState(1); let imgRatio = ratio; // 本地资源 获取图片比例 if (typeof source === "number") { const imgAsset = Image.resolveAssetSource(source); imgRatio = imgAsset.height / imgAsset.width; } // 图片高度 const imgHeight = typeof height === 'number' ? height : width * imgRatio; // uri资源,获取图片比例 useEffect(() => { if (typeof source === 'object') { const sourceAsset = source as ImageURISource; if (sourceAsset.uri) Image.getSize(sourceAsset.uri, (width, height) => { setRatio(height / width); }) } }, []) // 返回图片高度 useEffect(() => { if (setHeight) setHeight(imgHeight); }, [imgHeight]); return { imgHeight, } } export default { useData }