react+markdown+latex渲染展示

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;

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值