前端react项目中直接导入markdown文件

CodeBlock.js

import React from 'react';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { tomorrowNightEighties } from 'react-syntax-highlighter/dist/esm/styles/hljs';
import { Form } from 'antd';

class CodeBlock extends React.PureComponent {
  render() {
    const { value } = this.props;

    return (
      <SyntaxHighlighter language="" style={tomorrowNightEighties}>
        {value}
      </SyntaxHighlighter>
    );
  }
}

export default Form.create()(CodeBlock);

Help.js

import React, { Component } from 'react';
import { Card, Form } from 'antd';
import ReactMarkdown from 'react-markdown';
import codeBlock from './CodeBlock';
import AppMarkdown from './help.md';
import 'github-markdown-css';

@Form.create()
class Help extends Component {
  state = {
    markdown: '',
  };

  componentWillMount() {
    fetch(AppMarkdown)
      .then(res => res.text())
      .then(text => this.setState({ markdown: text }));
  }

  render() {
    const { markdown } = this.state;

    return (
      <div className={styles.advancedForm}>
        <Card className={styles.card} bordered={false}>
          <ReactMarkdown
            className="markdown-body"
            source={markdown}
            escapeHtml={false}
            renderers={{
              code: codeBlock,
            }}
          />
        </Card>
      </div>
    );
  }
}

export default Help;

参照出处:
https://github.com/conorhastings/react-syntax-highlighter/blob/master/README.md
https://stackoverflow.com/questions/42928530/how-do-i-load-a-markdown-file-into-a-react-component

猜你喜欢

转载自blog.csdn.net/weixin_34218890/article/details/88248814