如何在 Astro 中通过 props 导入带有传递名称的 svg 图像?

问题描述 投票:0回答:1

我有一个组件,可以从道具中分配标题、描述和图像。我正在使用 JSON 数组进行迭代以创建此组件的多个实例并添加图像。

我在 Astro 中使用图像时遇到两个问题 -

问题 1:当使用不带导入语法的直接路径图像时,Astro 会忽略构建时的图像。

<img 
    class="spec-logo linear-gradient"
    src={'../assets/specifications/'+imgname+'.svg'} 
    alt={title}/>

所以我阅读了其他 SF 帖子,并了解到导入语法可以缓解这个问题。

现在我有其他问题,因为我不知道如何使用导入语法动态导入图像

问题 2:内联导入语法无法按照此处解释的方式工作 -

我使用了img标签

<img class="spec-logo linear-gradient" src={import('../assets/specifications/battery.svg')} <--- alt={title}/> error -- 'Promise<typeof import("*.svg")>' is not assignable to type 'string'
我尝试过的另一个解决方案是 -

<Fragment set:html={import('../assets/specifications/battery.svg?raw')} />
这是渲染[object object]

我厌倦的第三个也是最后一个解决方案是这个 -

<svg class="w-6 h-6"> <use xlink:href={import('../assets/specifications/battery.svg') + '#icon-id'}></use> </svg>
以上均不起作用 - 

image svg astrojs
1个回答
0
投票
我在阅读

此博客后找到的解决方案如下 -

interface Props { title: string; description: string; imgsrc: string; } const { title, description, imgsrc } = Astro.props as Props; const { default: innerHTML } = await import(`../assets/specifications/${imgsrc}.svg?raw`); <span class="card-title">{title}</span> <span class="card-value linear-gradient">{description}</span> <Fragment set:html={innerHTML} class="spec-logo"/>

编辑:看起来效果很好,但是当我构建项目并检查预览时,所有这些图像都丢失了。问题仍然存在,因为这些图像没有包含在构建中。

© www.soinside.com 2019 - 2024. All rights reserved.