reactjs - 无法让highlight.js突出显示React渲染的代码

标签 reactjs markdown syntax-highlighting highlight.js

这是我的代码

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import MarkdownRenderer from 'react-markdown-renderer';

export default class Content extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content: ''
    };
  }

  componentWillMount() {
    let file_path = this.props.mdfPath;
    fetch(file_path)
      .then(response => response.text())
      .then(content => {
        this.setState({ content })
      })
    }

  render() {
    return(
      <div>
        <MarkdownRenderer markdown={this.state.content}/>
      </div>
    )
  }
}

该组件获取路径传递给它的任何 Markdown 文件的内容(通过 props),然后使用 react-markdown-renderer 将 markdown 转换为 HTML。

我已经下载了 hihglight.js文件并在我的 index.html 文件中指向它们。我还在index.html 中运行了函数 initHighlightingOnLoad() 。但是,当网站加载时,我的代码块不会突出显示。我不确定发生了什么事...有人可以帮忙吗?

这就是<MarkdownRenderer markdown={this.state.content} />输出到 DOM

<div>
  <h1>My Site</h1>
  <p>This is my site...</p>
  <pre>
    <code class="language-js">
      const msg = 'Welcome to My Site';
      console.log(msg); // Welcome to My SIte
    </code>
  </pre>
</div>

最佳答案

对于所有在上面没有找到任何有效答案并且没有成功使用 initHighlightingOnLoad 的人以及其他内置函数。

React:16.8.2 工作示例:

import hljs from "highlight.js";
import "./dracula.css";

class Preview extends Component {
  componentDidMount() {
    this.updateCodeSyntaxHighlighting();
  }

  componentDidUpdate() {
    this.updateCodeSyntaxHighlighting();
  }

  updateCodeSyntaxHighlighting = () => {
    document.querySelectorAll("pre code").forEach(block => {
      hljs.highlightBlock(block);
    });
  };

  render() {
    return (
    <div
        className="content"
        dangerouslySetInnerHTML={{ __html: this.props.parsedText }}
    />
    );
  }
}

请注意updateCodeSyntaxHighlighting应该在 componentDidMountcomponentDidUpdate每个使用 <pre><code>... 的组件中的方法标签。

关于reactjs - 无法让highlight.js突出显示React渲染的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49368326/

相关文章:

javascript - 根据图像的大小有条件地设置样式属性,通过 url 获取

javascript - 使用 React-router v4 进行导航

markdown - 如何更改美人鱼序列图中一个元素的颜色?

reactjs - React Tabs onClick 获取所选选项卡的索引

algorithm - 使用删除线将差异转换为 Markdown ?

image - 在 Github gist 中查看图像文件的推荐步骤不起作用

javascript - 让 VS Code 识别完整的 ES6 语法

javascript - 编写 Atom 编辑器插件,动画语法着色

用于在 BlogSpot 上写博客的 C# 语法荧光笔

reactjs - 使用 Semantic UI React,如何构建类似于 Stack Overflow 的标签输入?