“rexxars/react-markdown”插件用法或渲染 React markdown 的替代方案



我正在尝试渲染一些存储在数据库中的html,并在其中放置一个组件。

它看起来像这样:

import ReactMarkdown from 'react-markdown/with-html'; 
const inlineCode = (props) => <Gist id={props.value} />;
const source = '`7df0c9a5d794504a28bd3256b7bf5c4f` <p>asdasdasd</p><h1>title</h1>';

ReactMarkdown 是这样用的:

<ReactMarkdown source={source} renderers={{ inlineCode }} escapeHtml={false} />

结果是正确呈现,块也是,但不是,内容在块之外。

如果我用<div>包裹整个source,则<Gist/>呈现为文本,<p>/<h1>正确呈现。

我错过了什么?我正在尝试存储带有自定义组件的html,<Gist/>只是一个示例。也欢迎对(更多)合适的库提出建议。我想存储在数据库中然后在 React 组件中渲染的理想source示例:

<div>
  <p>
    <CustomReactComponent/>
    <br/>
    test
  </p>
  <Gist/>
</div>
好的,

我找到了这个库:https://github.com/probablyup/markdown-to-jsx

如果您的来源如下所示:

const source = `<gist id="yourIdHere" /> <h1>asdasdasd</h1>`;
<Markdown
  options={{
    overrides: {
      gist: {
        component: renderGist,
      },
    },
  }}
>
  {content}
</Markdown>

它将<Gist>和正常<h1>都呈现为 <h1 。如果您添加换行符,段落标签似乎会自动添加,并且像 # Title 之类的内容也会自动换行。

源代码中的<Gist>转换为小写,因此它只对overrides对象(再次小写)重要。以可预测的方式处理我所有的自定义内容和 html。

最新更新