gpt4 book ai didi

javascript - 如何在react组件上导入highlight.js?

转载 作者:行者123 更新时间:2023-11-28 03:41:00 25 4
gpt4 key购买 nike

我想在 React.js 组件中显示并突出显示一些“JSON”数据。

它可以工作,但问题是当组件刷新时,突出显示的代码消失。

我想澄清一下,我是这里的新手。

感谢您的支持。

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;

最佳答案

据我所知,函数调用 hljs.initHighlightingOnLoad(); 是激活突出显示的函数。如果您使用钩子(Hook),请在 useEffect 中调用该函数,或者如果您使用类,请在 componentDidMountcomponentDidUpdate 中调用该函数。

关于javascript - 如何在react组件上导入highlight.js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57311214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com