React Markdown-如何将自定义的简码呈现到组件中

问题描述 投票:1回答:1

我正在使用React Markdown(https://github.com/rexxars/react-markdown)渲染Markdown内容。

我想问一下如何呈现我们在降价促销中定义的特定短代码。

例如,在我的降价内容中,我可以插入此短代码[[ table product="mask" ]]

然后,React Markdown组件可以将其拾取,并呈现我之前定义的自定义组件(例如<Table product="mask" />)。

我已经阅读了文档,但找不到任何文档。如果您以前有这样做的经验,请告诉我。

非常感谢。

reactjs markdown shortcode
1个回答
0
投票

您将需要remark-shortcodes插件并定义一个renderers字段来告诉ReactMarkdown如何处理您的短代码:

const YourComponent = (content: string) => (
      <ReactMarkdown
        source={content}
        plugins={[
          [require("remark-shortcodes"), {startBlock: "[[", endBlock: "]]", inlineMode: true }]
        ]}
        renderers={{ shortcode: Shortcode }}
      />
)

const Shortcode = (props: any) => {
  /*
  props will looks something like:
    {
      "type": "shortcode",
      "identifier": "MailchimpForm",
      "attributes": { "id": "chfk2" }
    }
  see: https://github.com/djm/remark-shortcodes
  */
  switch (props.identifier) {
    case 'table':
      return <Table .../>;
    default:
      throw new Error('unknown shortcode')
  }
};

根据您要构建的内容,您可能需要startBlockendBlockinlineMode选项,也可能不需要。

© www.soinside.com 2019 - 2024. All rights reserved.