如何解决如何在react-markdown中使用自定义组件
上下文:我有一个Next.js的Chakra UI网站。我有一些用户提供的markdown内容,这些内容是在运行时从外部来源(例如GitHub README.md
进行回购)获取的。
现在,默认情况下,react-markdown(基于remarkjs)将HTML <img>
标记用于降价图像(![]()
)。我想在用户提供的降价中使用new <Image />
component released in Next.js 10。另外,我还想用相应的Chakra UI组件替换其他标签。
我该怎么做?
解决方案
// utils/parser.tsx
import Image from 'next/image';
export default function ImageRenderer({ src,alt }) {
return <Image src={src} alt={alt} unsized />;
}
,然后在所需页面中:
//pages/readme.tsx
import ReactMarkdown from 'react-markdown';
import imageRenderer from '../utils/parser';
// `readme` is sanitised markdown that comes from getServerSideProps
export default function Module({ readme }) {
return <ReactMarkdown allowDangerousHtml={true} renderers={{ image: imageRenderer }} children={readme} />
}
与其他元素相同...
解决方法
react-markdown可让您定义自己的渲染器。我最近做了类似的事情。我想使用图形和图形标题元素。因此,我创建了自己的图像渲染器react组件。
组件
export default function ImageRenderer(props) {
const imageSrc = props.src;
const altText = props.alt;
return (
<figure className="wp-block-image size-large is-resized">
<img
data-loading="lazy"
data-orig-file={imageSrc}
data-orig-size="1248,533"
data-comments-opened="1"
data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}"
data-image-title="builtin_vs_dotnetwarp"
data-image-description=""
data-medium-file={imageSrc + "?w=300"}
data-large-file={imageSrc + "?w=750"}
src={imageSrc + "?w=10241"}
alt={altText}
srcSet={imageSrc + "?w=1024 1024w," + imageSrc + "?w=705 705w," + imageSrc + "?w=150 150w," + imageSrc + "?w=300 300w," + imageSrc + "?w=768 768w," + imageSrc + "?1248w"}
sizes="(max-width: 707px) 100vw,707px" />
<figcaption style={{ textAlign: "center" }}>{altText}</figcaption>
</figure>
);
}
然后按以下方式使用该渲染器
<ReactMarkdown source={blogResponse.data.content} escapeHtml={false} renderers={{ "code": CodeBlockRenderer,"image": ImageRenderer }} />
renderers = {{“代码”:CodeBlockRenderer,“图像”:ImageRenderer}}是您提到自定义渲染器的地方。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。