在react-markdown中渲染HTML的任何方法

Kus*_*ish 16 markdown tinymce reactjs next.js

我正在使用tinymce 接受来自用户的降价数据。输出数据是html。我想在页面上显示该数据。我正在使用react-markdown。我可以在页面上看到数据,但它是 HTML 标签。有什么方法可以显示 HTML 页面而不是标签吗?

export default function ThePage() {
  const markdown = {
    description: "<p>Hello from the other </p>\n<p><strong>side</strong></p>",
  }

  return (
    <>
      <ReactMarkdown children={markdown.description} />
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

tro*_*mgy 43

ReactMarkdown组件用于渲染标记而不是 HTML标记。给定 HTML 输入,它只是转义它,这就是为什么您将其视为“源”,而不是格式化文本。

如果您需要将其与 HTML 一起使用,则需要应用插件,例如rehypeRaw

import ReactMarkdown from "react-markdown";
import rehypeRaw from "rehype-raw";

//...

export default function ThePage() {
  const markdown = {
    description: "<p>Hello from the other </p>\n<p><strong>side</strong></p>"
  }

  return (
    <>
      <ReactMarkdown children={markdown.description} rehypePlugins={[rehypeRaw]} />
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 2023年更新;为了防止 Typescript 抱怨,请使用 `rehypePlugins={[rehypeRaw] as any}` (3认同)