使用 react-markdown 解析 Markdown 中的下标

问题描述

我编写此语法是为了在 .md 文件获取下标:

   x_i
   x~i~

react-markdown 没有将其解析为下标。我发现包 remark-sub-super 和这个插件如下:

       <ReactMarkdown
          renderers={customrenderers }
          plugins={[remarkSubSuper]}
        >
          {blog.content}
        </ReactMarkdown>

这给了我一个错误TypeError: Cannot set property 'sub_super' of undefined。 我还在组件中添加skipHtml=true 并将其写入 .md 文件中:

  b<sub>i</sub>

这也不起作用。我正在使用 next.js

解决方法

使用下面的代码

<ReactMarkdown children={props.content} 
components={{ 
      em: ({ node,...props }) => { 
              if ( props.children[0] && typeof props.children[0] === 'string' && props.children[0].startsWith('^')) { 
                    return <sup>{props.children[0].substring(1)}</sup> 
               } 
              if ( props.children[0] && typeof props.children[0] === 'string' && props.children[0].startsWith('~')) { 
                    return <sub>{props.children[0].substring(1)}</sub> 
               } 
             return <i {...props} /> 
            },}}

基本上我们正在创建一个新的自定义插件。

您可能还喜欢阅读this story