【问题标题】:Type 'string' is not assignable to type 'ImageSourcePropType'类型“字符串”不可分配给类型“ImageSourcePropType”
【发布时间】:2021-02-22 12:09:08
【问题描述】:

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

问题

组件在某些时候有一个Image 标签,如下所示:xlinkHref="data:image/png;base64,,然而,紧接着它有大约 474 行加密信息,或者至少我认为是这样。例如,这是第一行的前半部分:iVBORw0KGgoAAAANSUhEUgAAAeUAAAJwCAYAAAC3c3kPAAAAAXNSR0IArs4c6QAAQABJREFUeAH。 VS Code 自动将xlinkHreftag 突出显示为不正确,我得到标题中提到的错误:

类型“字符串”不可分配给类型“ImageSourcePropType”。

下面的错误信息提到:

预期的类型来自属性“xlinkHref”,该属性在此处声明类型为“IntrinsicAttributes & IntrinsicClassAttributes> & Readonly & Readonly<...>”

我不是一个专业的程序员,无法理解错误试图告诉我什么,所以如果有人愿意解释一下,那就意味着很多。

问题

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

提前非常感谢!

【问题讨论】:

    标签: typescript react-native svg


    【解决方案1】:

    也许有一种更“TypeScripting”的方式来做到这一点。

    /**
     * @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}

      【讨论】:

      • 我不敢相信我没有考虑过简单地打字的力量。非常感谢。
      猜你喜欢
      • 2023-02-03
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多