根据上面的答案,我使用TypeScript创建了一个功能组件,只下载一次图像(因为第二次会被缓存:https://reactnative.dev/docs/image#getsize),如果只传递一个值; 并且根据传递的属性计算高度和宽度。
import { useFocusEffect } from '@react-navigation/native';
import React from 'react';
import { ImageProps, ImageURISource } from 'react-native';
import { useIsMounted } from '../../hooks/is-mounted';
import { DrImageStyl } from './styled';
import { getImageSizes } from '../../utils/util';
interface DrSource extends ImageURISource {
uri: string;
}
interface DrImageProps extends ImageProps {
source: DrSource;
width?: number;
height?: number;
}
const DrImage: React.FC<DrImageProps> = ({
width: widthProp,
height: heightProp,
source,
...rest
}: DrImageProps) => {
const isMountedRef = useIsMounted();
const [sizes, setSizes] = React.useState({
width: widthProp,
height: heightProp,
});
useFocusEffect(
React.useCallback(() => {
const getImageSizesState = async () => {
try {
const { width, height } = await getImageSizes({
uri: source.uri,
width: widthProp,
height: heightProp,
});
if (isMountedRef.current) {
setSizes({ width, height });
}
} catch (error) {
console.log('Erro em dr-image getImageSizesState:', error);
}
};
getImageSizesState();
}, [widthProp, heightProp, source.uri])
);
return (
<>
{!!sizes.height && !!sizes.width && (
<DrImageStyl sizes={sizes} source={source} {...rest} />
)}
</>
);
};
export default DrImage;
我使用了一个钩子来确定在异步函数执行后,组件是否仍然挂载(useIsMounted):
import React from 'react';
export const useIsMounted = (): React.MutableRefObject<boolean> => {
const isMountedRef = React.useRef(false);
React.useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
return isMountedRef;
};
我使用了styled-components模块来制作组件的CSS(
DrImageStyl):
import React from 'react';
import styled, { css } from 'styled-components/native';
interface Sizes {
width?: number;
height?: number;
}
interface DrImageStylProps {
sizes: Sizes;
}
export const DrImageStyl = styled.Image<DrImageStylProps>`
${({ sizes }) => {
const { width, height } = sizes;
return css`
${width ? `width: ${width}px;` : ''}
${height ? `height: ${height}px;` : ''}
`;
}}
`;
我将计算其他图片尺寸的代码(getImageSizes)单独分离出来:
import { Image } from 'react-native';
interface GetImageSizesParams {
uri: string;
height?: number;
width?: number;
}
export function getImageSizes({
height: heightParam,
width: widthParam,
uri,
}: GetImageSizesParams): Promise<{
width: number;
height: number;
}> {
return new Promise((resolve, reject) => {
function onSuccess(width: number, height: number) {
let widthResolve: number | undefined;
let heightResolve: number | undefined;
if (widthParam && !heightParam) {
widthResolve = widthParam;
heightResolve = height * (widthParam / width);
} else if (!widthParam && heightParam) {
widthResolve = width * (heightParam / height);
heightResolve = heightParam;
} else {
widthResolve = widthParam;
heightResolve = heightParam;
}
resolve({
width: widthResolve as number,
height: heightResolve as number,
});
}
function onError(error: any) {
reject(error);
}
try {
Image.getSize(uri, onSuccess, onError);
} catch (error) {
console.log('error', error);
}
});
}