gpt4 book ai didi

reactjs - 如何在 react-markdown 中使用自定义组件

转载 作者:行者123 更新时间:2023-12-05 02:04:11 35 4
gpt4 key购买 nike

上下文:我有一个 Next.js网站 Chakra UI .我有一些用户提供的 Markdown 内容,这些内容是在运行时从外部来源(例如,GitHub README.md 用于存储库)获取的。

现在,默认情况下,react-markdown (基于 remarkjs )使用 HTML <img> Markdown 图像的标签(![]())。我想使用 new <Image /> component released in Next.js 10在用户提供的 Markdown 中。此外,我还想用相应的 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 允许您定义自己的渲染器。我最近做了类似的事情。我想使用 figure 和 figurecaption 元素。因此,我创建了自己的图像渲染器 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="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}"
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={{ "code": CodeBlockRenderer, "image": ImageRenderer }} 是您提到自定义渲染器的地方。

关于reactjs - 如何在 react-markdown 中使用自定义组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64647763/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com