嘿伙计们,我有 sime markdown (mdx) 文件,我想将其与 svg 一起使用。我知道在盖茨比中渲染动态的任何东西都可能很棘手..对于盖茨比图像,您通常必须过滤出正确的结果。但对于 svgs 特别是我想知道如何根据我的 markdown 中的 frontmatter 动态渲染它们。我尝试做
<img src={svgpath} />
但无济于事。现在我的 svgs 已作为组件导入,在我的配置中使用它:
"gatsby-transformer-sharp",
{
resolve: "gatsby-plugin-react-svg",
options: {
rule: {
include: /assets/
}
}
},
我不知道动态导入文件或动态渲染与 markdown 中的名称匹配的适当 svg 的方法。这是我的 markdown 中 frontmatter 的示例:
---
title: Pediatric Dentistry
slug: pediatric-dentistry
svgPath: '../images/assets/dental.svg'
---
我怎样才能在我的模板文件中为每个特定的 Markdown 文件动态显示正确的 svg?我可以动态渲染 png、jpg 等,但由于 svgs 特定需要使用 gatsby 中的 transofmrer-sharp 作为组件导入,所以我很挣扎。预先感谢!
我想到的一件事是创建一种映射,一种导入所需组件的
key
-value
对。比如:
import Dental from '../images/assets/dental.svg';
import OtherSvg from '../images/assets/otherSvg.svg';
import OtherLogo from '../images/assets/otherLogo.svg';
const SVGMapper = {
'dental': Dental,
'otherSvg': OtherSvg,
'otherLogo': OtherLogo,
};
export default SVGMapper;
等等...
然后,要从 Markdown 中渲染它,您只需要:
let SVGComponent = SVGMapper['dental'];
return <SVGComponent />;
您可以使用循环或任何您想要的方式使其动态化。
如果需要,您甚至可以更改路径的
key
(dental
、otherSvg
和 otherLogo
)。方法完全相同,您需要更改 SVG 路径的 key
并渲染 SVGMapper[svgPath]
我发现最好的方法是使用“gatsby-plugin-svgr”...
只要您从原始 svg 文件中删除这些属性,就可以完全控制 svg 填充、宽度和高度。之后,您只需根据一组选项或可能性有条件地渲染某个图标即可。
svgs 像这样导入:
import { ReactComponent as Email } from '../../images/svgs/mail.svg';
然后它们可以像这样渲染为组件:
<Email />
然后使用标签以传统CSS为目标