The*_*ner 2 javascript markdown node.js reactjs
我正在使用一个名为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;
Run Code Online (Sandbox Code Playgroud)
这工作正常,除了个别段落是用标准<p>标签呈现的。在我的用例中,我需要将它们呈现为自定义组件,例如<MyParagraph>. 换句话说,请考虑以下输入文本:
This is paragraph one.
Lorem ipsum doler sit.
This is paragraph two.
Run Code Online (Sandbox Code Playgroud)
react-markdown将markdown渲染为:
<p>This is paragraph one.</p>
<p>Lorem ipsum doler sit.</p>
<p>This is paragraph two.</p>
Run Code Online (Sandbox Code Playgroud)
我需要它:
<MyParagraph>This is paragraph one.</MyParagraph>
<MyParagraph>Lorem ipsum doler sit.</MyParagraph>
<MyParagraph>This is paragraph two.</MyParagraph>
Run Code Online (Sandbox Code Playgroud)
这个模块甚至可能吗?还是我应该使用其他东西?
小智 6
I found this: https://github.com/rexxars/react-markdown/issues/218
The renderers property is helpful to create custom component.
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"));
Run Code Online (Sandbox Code Playgroud)
Here is the codesandbox of above code: https://codesandbox.io/s/awesome-surf-r05kb?fontsize=14