React 集成Prism代码高亮

2021-08-16  本文已影响0人  BigTaiYang大太阳
import React, {Component} from 'react';
import Prism from 'prismjs';
import 'prismjs/themes/prism.css';
import 'prismjs/components/prism-java'; // for java
import 'prismjs/components/prism-python'; // for python

class PrismHighlighter extends Component {

    constructor(props) {
        super(props);
        this.ref = React.createRef();
    }

    componentDidMount() {
        this.highlight();
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        this.highlight();
    }

    highlight() {
        Prism.highlightElement(this.ref.current);
    }

    render() {
        const {language, plugins, code} = this.props;
        return (
            <pre className={!plugins ? "" : plugins.join(" ")}>
                <code ref={this.ref} className={`language-${language}`}>
                    {code}
                </code>
            </pre>
        );
    }
}

export default PrismHighlighter;

使用

render() {
        const code = `String name = "张三";`;
        return (
            <PrismHighlighter
                language={"java"}
                code={code}
                plugins={["line-numbers"]}
            />
        );
    }

如果使用插件以及不同语言支持,需要引入对应的js和样式

import 'prismjs/plugins/line-numbers/prism-line-numbers';
import 'prismjs/plugins/line-numbers/prism-line-numbers.css'
上一篇下一篇

猜你喜欢

热点阅读