React

react实现markdown

2019-07-03  本文已影响0人  宁大通信狗

一、概要

最近想实现个人博客,博客文章想采用markdown来进行编辑。参考了网上一些markdown的实现,要么都是比较老的方法,要么是vue的方法,而相对于vue来说,我更熟悉react一下,所以这些方法都不太让我满意。于是自己摸索了一种方法来实现react中的markdown效果。

二、所需第三方库

1. react-markdown

1) 作用

用来转换markdown语法

2) 下载

$ npm install react-markdown --save

2. highlight.js

1) 作用

博客中不仅包含普通文本,还有代码,光使用react-markdown无法实现代码高亮,所以这里就需要用到highlight.js

2) 下载

$ npm install highlight.js --save

3. prop-types

1) 作用

稍后定义代码块组件时会用到

2) 下载

$ npm install prop-types --save

三、代码编写

1. 定义CodeBlock组件,以供稍后调用

1) 首先引入库

import React,{PureComponent} from 'react'; //引入react
import PropTypes from 'prop-types';  //引入prop-types
import hljs from 'highlight.js'  
import 'highlight.js/styles/androidstudio.css'  //代码块样式

这里引入了androidstudio样式,也可以引入别的样式:

import 'highlight.js/styles/xxx.css';

这里的xxx具体有哪些,可以去highlightjs的官网查看https://highlightjs.org/

样式预览.png
点击图片中箭头指向的位置切换样式进行预览,然后用“style:”后面的名字替换上面代码块中的xxx

2)代码主体

代码主体参考https://github.com/rexxars/react-markdown/blob/master/demo/src/code-block.js

class CodeBlock extends PureComponent{
    constructor(props){
        super(props);
        this.setRef = this.setRef.bind(this)
    }
    setRef(el){
        this.codeEl = el
    }
    componentDidMount() {
        this.highlightCode()
    }
    componentDidUpdate(prevProps, prevState, snapshot) {
        this.highlightCode()
    }
    highlightCode(){
        hljs.highlightBlock(this.codeEl)
    }
    render() {
        return(
            <pre>
                <code ref={this.setRef} className={`language-${this.props.language}`}>
                    {this.props.value}
                </code>
            </pre>
        )
    }
}
CodeBlock.defaultProps = {
    language:''
};
CodeBlock.protoTypes = {
    value:PropTypes.string.isRequired,
    language: PropTypes.string
};
export default CodeBlock;

2. 编写简单的组件Editor进行展示

1) 先引入库

import React,{Component} from 'react';
import MarkDown from 'react-markdown/with-html'; 

上面需要注意引入的是react-markdown/with-html而不是react-markdown。

import CodeBlock from '../../../components/codeBlock' //代码块组件

这里引入我们刚刚写好的代码块组件,这里的引入路径根据自己的代码来写

2) 代码主体

代码主体参考https://github.com/rexxars/react-markdown/blob/master/demo/src/demo.js
对原代码进行了简化以便于理解

class Editor extends Component{
    constructor(props){
        super(props);
        this.state={
            content:""
        }
    }
    onChange = (e) => {
        this.setState({
            content:e.currentTarget.value
        })
    };
    render() {
        return(
            <div className="result-pane">
                <textarea onChange={this.onChange}/>
                <MarkDown className="result" source={this.state.content} renderers={{code:CodeBlock}}/>
            </div>
        )
    }
}
export default Editor;

可以在代码主体中看到,在<MarkDown/>组件里有个renders属性,就是这里指向了我们之前写的代码块组件。

3) 组件调用

编写完上述代码,就可以import Editor组件来展示效果了,这里就不多说了,如果需要可以留言

四、效果展示

想看看效果的话,可以进入我的个人网站https://www.nbucedog.com/blog

上一篇 下一篇

猜你喜欢

热点阅读