我想包装的图像组件的反应-本土化。但是,会出现一条错误消息,表示“uri”属性不存在。这一切为什么要发生?
import React from 'react';
import { Image as DefaultImage, ImageProps } from 'react-native';
import { PromiseFn, useAsync } from 'react-async';
type ImageSize = {
width: number;
height: number;
};
const getImageSize = (uri: string) => {
return new Promise<ImageSize>((resolve, reject) => {
DefaultImage.getSize(
uri,
(width, height) => {
resolve({ width, height });
},
(error) => {
reject(error);
}
);
});
};
const promiseFn: PromiseFn<ImageSize> = async ({ uri }) =>
await getImageSize(uri);
export function Image(props: ImageProps) {
const { source } = props;
const { data, error, isPending } = useAsync<ImageSize>({
promiseFn: promiseFn,
uri: source.uri, // Property 'uri' does not exist on type 'ImageSourcePropType'.
// Property 'uri' does not exist on type 'number'.ts(2339)
});
return (
<DefaultImage
style={[{ width: data?.width, height: data?.height }, props.style]}
{...props}
/>
);
}我尝试了一种不同的方法,但有另一个错误。
const isImageURISource = (
source: ImageURISource | ImageURISource[] | ImageRequireSource
) => {
if ('uri' in source) {
return source; // The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)
}
};发布于 2020-09-18 23:37:17
我不确定这是一个很好的解决方案,但我也是这样解决同样的问题的。
基本上重写source类型。
import {
ImageProps as DefaultImageProps,
ImageURISource,
} from 'react-native';
type ImageProps = DefaultImageProps & {
source: ImageURISource;
};发布于 2020-09-18 19:25:55
下面是我在ImageSourcePropType上找到的github的定义。我看上去ImageSourcePropType可以是一个数字或数组,在这种情况下,它将没有一个uri属性。
const ImageURISourcePropType = PropTypes.shape({
uri: PropTypes.string,
bundle: PropTypes.string,
method: PropTypes.string,
headers: PropTypes.objectOf(PropTypes.string),
body: PropTypes.string,
cache: PropTypes.oneOf([
'default',
'reload',
'force-cache',
'only-if-cached',
]),
width: PropTypes.number,
height: PropTypes.number,
scale: PropTypes.number,
});
const ImageSourcePropType = PropTypes.oneOfType([
ImageURISourcePropType,
// Opaque type returned by require('./image.jpg')
PropTypes.number,
// Multiple sources
PropTypes.arrayOf(ImageURISourcePropType),
]);https://stackoverflow.com/questions/63960970
复制相似问题