next.js 如何在highlightjs中切换浅色主题和深色主题?

33qvvth1  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(114)

我正在使用highlightjs来突出显示代码块的NextJS应用程序。在我的应用程序中,我有一个黑暗模式和光明模式。现在,我们如何以编程方式在黑暗模式和模式之间切换?
我正在使用highlightAll()方法高亮显示。

sf6xfgos

sf6xfgos1#

添加明暗模式样式:style.css

/* Light Mode */
.light-mode {
  background-color: #ffffff;
  color: #000000;
}

/* Dark Mode */
.dark-mode {
  background-color: #1e1e1e;
  color: #ffffff;
}

字符串
在亮模式和暗模式之间切换的组件示例。

// Your component file

import { useState } from 'react';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css'; // Default theme, choose a light one
import 'highlight.js/styles/github-dark.css'; // Dark theme from Highlight.js

const CodeHighlighter = () => {
  const [isDarkMode, setIsDarkMode] = useState(false);

  const toggleMode = () => {
    setIsDarkMode(!isDarkMode);
    highlightCode();
  };

  const highlightCode = () => {
    const codeBlocks = document.querySelectorAll('pre code');
    hljs.highlightAll();

    // Load corresponding theme based on mode
    const themePath = isDarkMode ? 'highlight.js/styles/github-dark.css' : 'highlight.js/styles/github.css';
    loadTheme(themePath);
  };

  const loadTheme = (path) => {
    const existingTheme = document.querySelector('#highlight-theme');
    if (existingTheme) {
      existingTheme.href = path;
    } else {
      const theme = document.createElement('link');
      theme.rel = 'stylesheet';
      theme.id = 'highlight-theme';
      theme.href = path;
      document.head.appendChild(theme);
    }
  };

  return (
    <div>
      <button onClick={toggleMode}>Toggle Mode</button>
      <pre>
        <code className="javascript">
          {`const example = () => {
            // Your code here
          };`}
        </code>
      </pre>
    </div>
  );
};

export default CodeHighlighter;

相关问题