美文网首页
React 集成Prism代码高亮

React 集成Prism代码高亮

作者: BigTaiYang大太阳 | 来源:发表于2021-08-16 12:29 被阅读0次
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'

相关文章

网友评论

      本文标题:React 集成Prism代码高亮

      本文链接:https://www.haomeiwen.com/subject/eoymbltx.html