简体   繁体   English

React Markdown - 如何将自定义短代码渲染到组件中

[英]React Markdown - How to render custom shortcode into component

I am using React Markdown ( https://github.com/rexxars/react-markdown ) to render markdown content.我正在使用 React Markdown ( https://github.com/rexxars/react-markdown ) 来呈现 Markdown 内容。

I'd like to ask how to render specific shortcode that we define in the markdown.我想问一下如何呈现我们在降价中定义的特定短代码。

For example, in my markdown content, I could insert this shortcode [[ table product="mask" ]]例如,在我的降价内容中,我可以插入这个短代码[[ table product="mask" ]]

Then the React Markdown component could pick it up, and render a custom component that I've defined before (such as <Table product="mask" /> ).然后 React Markdown 组件可以选择它,并呈现我之前定义的自定义组件(例如<Table product="mask" /> )。

I've read through the documentation but could not find any.我已经通读了文档,但找不到任何文档。 Please let me know if you have experience doing this before.如果您以前有过这样做的经验,请告诉我。

Thank you so much.非常感谢。

You will need the remark-shortcodes plugin and define a renderers field to tell ReactMarkdown what to do with your shortcodes:您将需要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')
  }
};

You might or might not need the startBlock , endBlock , and the inlineMode options depending on what you are building.您可能需要也可能不需要startBlockendBlockinlineMode选项,具体取决于您正在构建的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM