如何从React组件渲染Markdown?

the*_*ist 35 javascript markdown reactjs

我的文档是用markdown编写的,我想将这些文件从我的JSX(ES6 + CommonJS)代码渲染到React组件中.我怎样才能做到这一点?

例如,我有styles.markdown,我想将它渲染成<p>标签.

And*_*ena 51

只需创建一个简单的React组件,它就可以调用Markdown解析器.JavaScript有两个非常好的:

现在您可以创建这样的组件:

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}} />;
    }
});
Run Code Online (Sandbox Code Playgroud)

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

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

  • 不知道什么时候改变了,但我今天正在解决这个问题,现在React似乎需要一个带有__html字段的对象而不仅仅是一个字符串(例如`dangerouslySetInnerHTML = {{__ html:markdown}}`).此外,即使它可能与此处提出的问题无关,但值得注意的是,建议使用降价库清理输入以避免XSS,如果其中任何一个可能不受信任(例如`var markdown = marked .parse(this.props.markdown,{sanitize:true});`). (9认同)

okl*_*las 16

react-markdown包含Markdown组件的包将是不错的选择:

import React from 'react'
import Markdown from 'react-markdown'

var src = "# Load the markdown document"

React.render(
    <Markdown source={src} />,
    document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)


Yev*_*nov 9

从markdown文本呈现html的Markdown组件示例,加载数据的逻辑应该在单独的store/parent组件/中实现.我使用标记包将markdown转换为html.

import React from 'react';
import marked from 'marked';

export default class MarkdownElement extends React.Component {
  constructor(props) {
    super(props);

    marked.setOptions({
      gfm: true,
      tables: true,
      breaks: false,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: false
    });
  }
  render() {
    const { text } = this.props,
      html = marked(text || '');

    return (<div>
      <div dangerouslySetInnerHTML={{__html: html}} />
    </div>);
  }
}

MarkdownElement.propTypes = {
  text: React.PropTypes.string.isRequired
};

MarkdownElement.defaultProps = {
  text: ''
};
Run Code Online (Sandbox Code Playgroud)


pro*_*yup 6

我参加聚会有点晚了,但是我为上面提到的库写了一个竞争者库,它的另一个好处是不需要dangerouslySetInnerHtml黑客:https : //github.com/probablyup/markdown-to-jsx

  • 我今天尝试了“react-markdown”和“markdown-to-jsx”。长话短说:“markdown-to-jsx”轻了 5 倍,并且将其配置为使用安全的“noopener”默认值打开“_blank”链接要容易得多。请参阅 https://github.com/probouslyup/markdown-to-jsx/issues/259#issue-473110464 _(我基本上没有成功地使用 `react-markdown` 做到这一点)_ (2认同)

kpi*_*mov 5

尝试这样的事情:

import fs from 'fs';
import React, { Component, PropTypes } from 'react';

class Markdown extends Component {
    constructor() {
        super(props);
        this.state = { contents: '' };
        this.componentDidMount = this.componentDidMount.bind(this);
    }

    componentDidMount() {
        const contents = fs.readFileSync(this.props.path, 'utf8');
        this.setState({ contents });
    }

    render()
        return (
            <div>
                {this.state.contents.split('\n').map((line, i) =>
                    line ? <p key={i}>{line}</p> : <br key={i} />)}
            </div>
        );
    }
}

Markdown.propTypes = { path: PropTypes.string.isRequired };

React.render(<Markdown path='./README.md' />, document.body);
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用的是ES7 +功能:

import fs from 'fs';
import React, { Component, PropTypes } from 'react';

class Markdown extends Component {
    static propTypes = { path: PropTypes.string.isRequired };

    state = { contents: '' };

    componentDidMount = () => {
        const contents = fs.readFileSync(this.props.path, 'utf8');
        this.setState({ contents });
    };

    render() {
        return (
            <div>
                {this.state.contents.split('\n').map((line, i) =>
                    line ? <p key={i}>{line}</p> : <br key={i} />)}
            </div>
        );
    }
}

React.render(<Markdown path='./README.md' />, document.body);
Run Code Online (Sandbox Code Playgroud)

如果运行在客户端,则需要使用brfs转换才能使用fs.readFileSync。