如何在Astro.js中渲染从MDX导出的组件?渲染失败求助
问题
我有如下MDX文件,希望在其他位置渲染其中导出的foo组件:
--- title: Hi, World! --- export const title = 'My first MDX post' export const foo = <h1>adsf</h1> # {title}
通过以下代码获取该MDX文件:
--- const matches = await Astro.glob('../../content/blog/*.mdx'); const foo = matches[0].foo ---
得到的foo对象为:
{ 'astro:jsx': true, type: 'h1', props: { children: "adsf" }, [Symbol(astro:renderer)]: 'astro:jsx' }
但在.astro文件中使用{foo}和<foo/>均无法渲染该组件,请问是否有可行的渲染方法?
可行的渲染方法
提供两种直接有效的渲染方式:
方法一:使用Astro内置的<Component>组件
Astro专门提供了用于渲染JSX对象的<Component>组件,只需传入foo对象的type和props即可:
--- const matches = await Astro.glob('../../content/blog/*.mdx'); const foo = matches[0].foo; --- <Component is={foo.type} {...foo.props} />
方法二:手动解构属性后渲染
也可以直接解构foo对象的属性,用解构出的标签和props渲染元素:
--- const matches = await Astro.glob('../../content/blog/*.mdx'); const { type: FooTag, props } = matches[0].foo; --- <FooTag {...props} />
内容的提问来源于stack exchange,提问作者ZeeXoc
相关产品推荐
相关产品推荐

