首页 > 解决方案 > 在没有 MDX 的 Markdown 中插入一个 React 组件

问题描述

如何<MyReactComponent />在降价段落中插入?

  1. 我需要它是通用的——也就是说,markdown 可能被一个非反应感知程序解析,在这种情况下它应该被忽略。
  2. react 组件不需要参数(我不需要向它传递数据,只需要在 markdown 中指明它的去向)

我正在将 NextJS 与来自无头 CMS 的数据一起使用,如下所示:

import marked from 'marked';
import MyReactComponent from './myComponent';

function Content({markdownContent}){
  return(
    <div className="content">
      <div dangerouslySetInnerHTML={{ __html: marked(markdownContent) }} />;
      // squirt MyReactComponent into appropriate place above...
    </div>
  )
}

我故意使用“标记”库,因为它轻巧且基本......我不想使用像 mdx 这样重的东西,或者复杂的......我只需要在降价中替换某种类型的占位符。

标签: reactjsmarkdown

解决方案


如果你的 markdown 中有一个带有唯一标识符的元素,你可以设置一个useEffect钩子来更新 dom 。ReactDOM.render

这是一个概念证明:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import marked from "marked";

const MyComponent = () => <span>⭐&lt;/span>;

const markdownContent = `
# MyComponent

Testing
`;

function App() {
  const [initialized, setInitialized] = useState(false);
  useEffect(() => {
    const el = document.getElementById("mycomponent");
    if (el) {
      ReactDOM.render(<MyComponent />, el); // you can pass props as usual
    }
    setInitialized(true);
  }, []);
  return (
    <div
      style={{ opacity: initialized ? 1 : 0 }}
      dangerouslySetInnerHTML={{ __html: marked(markdownContent) }}
    />
  );
}

默认情况下,marked在发出标题时将包含一个 id 属性。这就是为什么我使用标题作为 React 组件的占位符。诀窍是知道如何marked生成 ID。

你可以玩这个 CodeSandbox:

编辑 insert-a-react-component-inside-markdown-without-mdx


推荐阅读