将 Markdown 文本转换为 React 组件

IT技术 javascript node.js reactjs markdown
2021-05-14 04:29:54

我正在使用一个名为react-markdown的 npm 包将一段 Markdown 文本转换为 HTML 代码:

import React, { PureComponent } from 'react';
import ReactMarkdown from 'react-markdown';

let body = '## Some markdown text in multiple paragraphs';

class Post extends PureComponent {
  render() {
    <ReactMarkdown source={body} />
  }
}

export default Post;

这工作正常,除了个别段落是用标准<p>标签呈现的在我的用例中,我需要将它们呈现为自定义组件,例如<MyParagraph>. 换句话说,请考虑以下输入文本:

This is paragraph one.

Lorem ipsum doler sit.

This is paragraph two.

react-markdownmarkdown渲染为:

<p>This is paragraph one.</p>

<p>Lorem ipsum doler sit.</p>

<p>This is paragraph two.</p>

我需要它:

<MyParagraph>This is paragraph one.</MyParagraph>

<MyParagraph>Lorem ipsum doler sit.</MyParagraph>

<MyParagraph>This is paragraph two.</MyParagraph>

这个module甚至可能吗?还是我应该使用其他东西?

1个回答

我发现了这个:https : //github.com/rexxars/react-markdown/issues/218

renderers属性有助于创建自定义组件。

import ReactDOM from "react-dom";
import React, { PureComponent } from "react";
import ReactMarkdown from "react-markdown";

let body =
  "## Some markdown text in multiple paragraphs\n\nAnd this is a paragraph 1\n\nAnd this is a paragraph 2\n\nAnd this is a paragraph 3";

const MyParagraph = props => (
  <p>This is inside MyParagraph, and the value is {props.children}</p>
);

// see https://github.com/rexxars/react-markdown#node-types
const renderers = {
  paragraph: props => <MyParagraph {...props} />
};

class Post extends PureComponent {
  render() {
    return <ReactMarkdown source={body} renderers={renderers} />;
  }
}

export default Post;

ReactDOM.render(<Post />, document.getElementById("root"));

这是上面代码的代码和框:https ://codesandbox.io/s/awesome-surf-r05kb?fontsize =14