如何从React组件渲染Markdown? [英] How do I render Markdown from a React component?

查看:465
本文介绍了如何从React组件渲染Markdown?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档以markdown编写,我想将这些文件从JSX(ES6 + CommonJS)代码渲染到React组件中.我该如何实现?

I have my documentation written in markdown and I would like to render those files from my JSX (ES6+CommonJS) code into React components. How can I achieve this?

例如,我有styles.markdown,我想将其呈现为<p>标签.

For example I have styles.markdown and I would like to render it into a <p> tag.

推荐答案

您可以使用 React-Markdown :

const React = require('react')
const ReactDOM = require('react-dom')
const ReactMarkdown = require('react-markdown')

const input = '# This is a header\n\nAnd this is a paragraph'

ReactDOM.render(<ReactMarkdown source={input} />, document.getElementById('container'))

或者...您可以仅创建一个简单的React组件,该组件包装对Markdown解析器的调用. 有两个非常好的JavaScript代码:

Or... You can just create a simple React component that wraps a call to a Markdown parser. There are two very good ones for JavaScript:

  • Remarkable
  • Marked

现在,您可以创建一个像这样的组件:

Now, you can create a component like this:

var MarkdownViewer = React.createClass({
    render: function() {
        // pseudo code here, depends on the parser
        var markdown = markdown.parse(this.props.markdown);
        return <div dangerouslySetInnerHTML={{__html:markdown}} />;
    }
});

以前曾经有一个,但是似乎不再维护了: https://github.com/tcoopman/markdown-react

There used to have one already, but it doesn't seem to be maintained anymore: https://github.com/tcoopman/markdown-react

此外,如果您需要React Markdown编辑器,请签出: react-mde .免责声明:我是作者.

Also, if you need a React Markdown Editor, check out: react-mde. Disclaimer: I am the author.

这篇关于如何从React组件渲染Markdown?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆