【问题标题】:Any way to render HTML in react-markdown在 react-markdown 中呈现 HTML 的任何方式
【发布时间】:2022-01-01 11:58:40
【问题描述】:

我正在使用 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} />
    </>
  );
}

【问题讨论】:

    标签: reactjs next.js tinymce markdown


    【解决方案1】:

    是的,您可以使用react-render-markup 参见示例:

    import { Markup } from "react-render-markup";
     export default function App(){
     return(<Markup markup={markdown.description} />)
     }
    

    【讨论】:

    • 如果你只有 HTML 而不是 markdown + HTML,这是最好的解决方案
    【解决方案2】:

    ReactMarkdown 组件用于渲染标记 down,而不是 HTML 标记 up ?。给定 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]} />
        </>
      );
    }
    

    【讨论】:

      【解决方案3】:

      是的,你可以;

      const [html, setHtml] = useState("<p>Hello from the other </p>\n<p><strong>side</strong></p>");
      

      这样使用

        <div
          dangerouslySetInnerHTML={{
            __html: html,
          }}
       
        ></div>
      

      【讨论】:

      • 这对于用户提供的输入是不安全的。
      猜你喜欢
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      • 2015-08-28
      • 2021-03-19
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      相关资源
      最近更新 更多