来自 this answer从stackoverflow,我得到了一个关于如何将svg作为ReactComponent导入并改变它们的颜色/宽度等的解决方案。
但是是否可以对动态导入做同样的事情?
我的功能组件:
import * as React from 'react';
import SvgIconComponent from './SvgIcon.Interface';
import {ReactComponent} from '*.svg';
const SvgIcon: React.FC<SvgIconComponent> =({width, color, name}) =>
{
import(`../../assets/icons/${name}.svg`).then((Icon) => {
return <Icon fill={color} width={width}/>
});
};
export default SvgIcon;
在当前的实现中,我得到了错误:TS2749: 'ReactComponent' refers to a value, but is being used as a type here. // .then((Icon as ReactComponent)
TS2604: JSX element type 'Icon' does not have any construct or call signatures. // .then(Icon)
最佳答案
我建议你使用process.env.PUBLIC_URL
渲染你的 svg。将所有 svg 文件放入 public
文件夹,假设在 public/svgFiles
.
然后您可以将其用作<img src={process.env.PUBLIC_URL + "/svgFiles/" + file_name} alt="project" />
由于公共(public)文件夹中的所有内容都包含在最终 build
中,您所有的 svg 文件以及您使用的路径都会得到处理,因为所有内容都将从公共(public)文件夹中引用,构建后路径不会更改。
关于javascript - 我可以使用动态 import() 表达式将 SVG 文件作为 react 组件导入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71100587/