[英]How to import highlight.js on react component?
I would like to display and highlight some "JSON" data in a React.js component. 我想在React.js组件中显示并突出显示一些“ JSON”数据。
It works, but the problem is when the component refresh, the highlighted code disappear. 它可以工作,但是问题是当刷新组件时,突出显示的代码消失了。
I want to clarify that I'm a newbie here. 我想澄清一下,我是这里的新手。
Thank you for your support. 谢谢您的支持。
import React from "react";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import json from "highlight.js/lib/languages/json";
hljs.registerLanguage("json", json);
hljs.initHighlightingOnLoad();
const JsonViewer = props => {
return (
<pre>
<code className="json">
{JSON.stringify(props.content, null, 2)}
</code>
</pre>
);
};
export default JsonViewer;
From what I see the function call hljs.initHighlightingOnLoad();
从我看到的函数调用hljs.initHighlightingOnLoad();
is the one activating the highlighting. 是激活突出显示的那个。 If you are using hooks call that function in useEffect
or if you are using classes call it in componentDidMount
and componentDidUpdate
. 如果使用钩子,请在useEffect
调用该函数,或者如果使用类,则在componentDidMount
和componentDidUpdate
调用该函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.