React:渲染语法高亮显示的代码块 [英] React : Rendering a syntax highlighted code block

查看:276
本文介绍了React:渲染语法高亮显示的代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React和JSX开发文章系统。我的文章有时会在其内容中包含代码示例。我已经实现了highlight.js来为这些块添加样式。我的主要问题是我的文章使用HTML标签,因此我使用React的dangerouslySetInnerHTML方法。这没关系,但当然我的代码块中的任何HTML代码都被解释为HTML。我想知道你们中是否有人对如何实现这一点有任何见解。我应该从我的内容中删除所有HTML并解析它(使用markdown),然后将其安全地呈现为文本吗?

I'm working on an article system using React and JSX. My articles sometimes have code examples within their content. I have implemented highlight.js to add style to these blocks. My main problem is that my articles use HTML tags, I therefore use React's dangerouslySetInnerHTML method. This works alright but of course any HTML code in my code blocks get interpreted as HTML. I was wondering if any of you had any insight on how I should implement this. Should I remove all HTML from my content and parse it (using markdown) before safely rendering it as text ?

感谢您阅读本文。

推荐答案

我的解决方案是在文章视图中实现像解析器一样的简单降价。我们的想法是使用正则表达式解析markdown并从这些结果中返回JSX元素。我不太擅长正则表达式(这可能会有所改进),但这里有:

My solution was to implement a simple "markdown" like parser within my article view. The idea is to parse the markdown using regex and return JSX elements from those results. I'm not so good at regular expressions (this could probably be improved) but here goes :

module.exports = React.createClass({
//this regex matchs \n\n, all wrapping ** **, wrapping ''' '''
mainRegex: /(\n\n|\*\*(?:[\s\S]*?)\*\*|'''(?:[\s\S]*?)''')/g,
titleRegex : /(?:\*\*([\s\S]*?)\*\*)/,
codeRegex : /(?:'''([\s\S]*?)''')/,

getInitialState: function() {
    return {
        content: []
    };
},

setContent: function() {
    if (this.props.htmlContent && !this.state.content.length) this.setState( {content: this.formatText(this.props.htmlContent) });
},

formatText: function(_text) {

    var _this = this;
    var _content = [];

    _text = _text.split(this.mainRegex);

    _text.forEach(function(_frag) {

        if (!/\n\n/g.test(_frag) ) {

            if (_this.titleRegex.test(_frag))  _content.push( {type: "h2", value: _frag.match(_this.titleRegex)[1] } );
            else if (_frag!=="") _content.push({type: "p", value: _frag});

        } else if (_this.codeRegex.test(_frag))  {

            _content.push( {type: "code", value: _frag.match(_this.codeRegex)[1] } );
        }

    });

    return _content;
},
render: function() {

    return <article>
        {this.state.content.map(this.renderText)}
    </article>;

},

renderText:function(_tag, i) {

    switch (_tag.type) {

        case "p":
            return <p key={i}>{_tag.value}</p>;
            break;

        case "h2":
            return <h2 key={i}>{_tag.value}</h2>;
            break;

        case "code":
            return <pre key={i}><code clasName="js">{_tag.value}</code></pre>;
            break;

    }

},

componentDidUpdate: function() {

    this.setContent();
    this.highlightCode();

},

highlightCode: function() {

    var _codeBlocks = document.getElementsByTagName('code');
    for (var i = 0, j = _codeBlocks.length; i<j; ++i) {
        hljs.highlightBlock(_codeBlocks[i]);
    }

}
});

这篇关于React:渲染语法高亮显示的代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆