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

问题描述

上下文:我有一个Next.jsChakra 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="{&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 = {{“代码”:CodeBlockRenderer,“图像”:ImageRenderer}}是您提到自定义渲染器的地方。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...