将Markdown文本转换为React组件

时间:2019-07-16 04:34:47

标签: javascript node.js reactjs markdown

我正在使用一个名为 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.

反应降价将降价呈现为:

<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>

这个模块有可能吗?还是我应该使用其他东西?

1 个答案:

答案 0 :(得分: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