类型'string'不能赋值给类型'ImageSourcePropType'。

6

背景

我正在尝试使用一个带有属性xlinkHref的SVG组件,它位于Image标签中。该文件是一个普通的SVG,但我将其转换为React Native组件(TSX),使用了https://react-svgr.com/playground/?native=true。我以前用过非常简单的带有相同方法的SVG图标,但没有一个具有xlinkHref属性。

问题

组件在某个时候会在其中包含一个Image标签,类似于这样:xlinkHref="data:image/png;base64,,然后紧接着就有大约474行加密信息,或者至少我认为是这样。例如,这是第一行的前一半:iVBORw0KGgoAAAANSUhEUgAAAeUAAAJwCAYAAAC3c3kPAAAAAXNSR0IArs4c6QAAQABJREFUeAHxlinkHref标记由VS Code自动标记为不正确,并出现了标题中提到的错误:

Type 'string' is not assignable to type 'ImageSourcePropType'。

下面是错误消息中提到的内容:

预期的类型来自于在此处声明的属性'xlinkHref',它位于'type'IntrinsicAttributes& IntrinsicClassAttributes<Component<ImageProps,任意,任意>>&Readonly&Readonly<...>''

我并不是一个专业的程序员,也无法理解这个错误试图告诉我的内容,所以如果有人能够解释一下,那就太好了。

问题

在React Native中是否可以使用具有此类属性和分配值的SVG组件,还是根本不兼容?我该如何解决它?这是一个已知问题还是我遇到了一个新的障碍?我在互联网上找不到关于这个特定问题的任何信息。

先谢谢了!

2个回答

2
也许有一种更适合 TypeScript 的方法来实现这个。
/**
 * @see https://reactnative.dev/docs/image#source
 */
export type ImageSourcePropType = ImageURISource | ImageURISource[] | ImageRequireSource;

/*
 * @see https://github.com/facebook/react-native/blob/master/Libraries/Image/ImageSourcePropType.js
 */
export interface ImageURISource {
    /**
     * `uri` is a string representing the resource identifier for the image, which
     * could be an http address, a local file path, or the name of a static image
     * resource (which should be wrapped in the `require('./path/to/image.png')`
     * function).
     */
    uri?: string | undefined;
    /**

我们可以看到,ImageSourcePropType 继承了类型 ImageURISource,后者声明了一个名为 uri 的成员,因此只需要一个带有 uri 属性的普通对象即可。
<Image style={...somestyle} source={{ uri: ...the_path_to_your_image }}/>

2

以下方法适用于我:xlinkHref={'...' as any}


我简直不敢相信我没有考虑到使用TypeScript的强大威力。非常感谢你。 - lwisi
3
这样做违背了 TypeScript 的初衷,不应该这样做。 - David Alford

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接