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

Max*_*ack 3 markdown reactjs remarkjs next.js chakra-ui

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

现在,默认情况下,react-markdown(基于remarkjs)使用 HTML<img>标签来标记图像 ( ![]())。我想在用户提供的 markdown 中使用Next.js 10 中发布的新组件。<Image />此外,我还想用相应的 Chakra UI 组件替换其他标签。

我该怎么做呢?

解决方案

// utils/parser.tsx

import Image from 'next/image';

export default function ImageRenderer({ src, alt }) {
  return <Image src={src} alt={alt} unsized />;
}

Run Code Online (Sandbox Code Playgroud)

然后在需要的页面中:

//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} />
}
Run Code Online (Sandbox Code Playgroud)

其他元素也一样...

Ram*_*hat 5

React-markdown 允许您定义自己的渲染器。我最近做了类似的事情。我想使用figure和figurecaption元素。所以,我创建了自己的图像渲染器反应组件。

成分

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>
    );
}
Run Code Online (Sandbox Code Playgroud)

我使用该渲染器如下

<ReactMarkdown source={blogResponse.data.content} escapeHtml={false} renderers={{ "code": CodeBlockRenderer, "image": ImageRenderer }} />
Run Code Online (Sandbox Code Playgroud)

renderers={{ "code": CodeBlockRenderer, "image": ImageRenderer }} 是您提到自定义渲染器的地方。