react+markdown+latex渲染展示
markdown-it实现代码高亮+代码背景
使用的github库
https://github.com/markdown-it/markdown-it
使用文档
https://markdown-it.docschina.org/
效果图
安装依赖
npm install markdown-it markdown-it-texmath highlight.js katex
组件代码
MarkdownWithLatex.tsx
import React, { useState } from 'react';
import MarkdownIt from 'markdown-it';
import texmath from 'markdown-it-texmath';
// import itCopy from 'markdown-it-copy';
import hljs from 'highlight.js';
import 'katex/dist/katex.min.css'; // 导入KaTeX的样式
import 'highlight.js/styles/default.css'; // 导入highlight.js的样式
import './styles.css'; // 导入自定义样式
const md = new MarkdownIt({
html: true,
linkify: true,
typographer: true,
highlight: function (str:string, lang:string) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(str, { language: lang }).value;
} catch (__) {}
}
return ''; // 使用默认的代码块样式
},
}).use(texmath);
interface MarkdownWithLatexProps {
markdownContent: string; // 添加类型注解为字符串
}
const MarkdownWithLatex: React.FC<MarkdownWithLatexProps> = ({ markdownContent }) => {
const html = md.render(markdownContent);
return (
<div
dangerouslySetInnerHTML={{ __html: html }}
/>
);
};
export default MarkdownWithLatex;
styles.css
/* 代码块样式 */
pre {
background-color: #f5f5f5; /* 背景颜色 */
padding: 1rem;
overflow-x: auto; /* 水平滚动条 */
border-radius: 4px;
position: relative; /* 添加相对定位 */
}
使用组件
import React, { useState } from 'react';
import MarkdownWithLatex from './MarkdownWithLatex';
import './styles.css'; // 导入自定义样式
const App = () => {
const markdownContent = `
# Markdown with LaTeX and code highlighting
This is a sample Markdown document with LaTeX formulas and code blocks with syntax highlighting.
Inline formula: $x^2 + y^2 = z^2$
Block formula:
$$
\\int_0^\\infty e^{-x} dx = 1
$$
Code block with syntax highlighting:
\`\`\`javascript
function add(a, b) {
return a + b;
}
\`\`\`
`;
const [copied, setCopied] = useState(false);
const handleCopyClick = () => {
navigator.clipboard.writeText(markdownContent).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 3000);
});
};
return (
<div>
<MarkdownWithLatex markdownContent={markdownContent} />
</div>
);
};
export default App;