react项目实现预览markdown,以及代码高亮

本文介绍如何在React项目中实现Markdown文本的预览及代码高亮功能,主要涉及react-syntax-highlighter和react-markdown两个库的使用方法,并提供了一种随项目主题切换亮暗主题的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

react项目实现预览markdown,以及代码高亮

前言

不少的react项目中需要实现markdown预览以及代码高亮的功能,效果如下。
在这里插入图片描述
在这里插入图片描述
上面图片展示的内容是我在个人项目中实现的效果,用到了两个库react-markdownreact-syntax-highlighter,一个用于预览markdown文本,另外一个用于代码高亮展示。

一、react-syntax-highlighter的使用

我下载的版本是15.4.5。
下面是我自己在项目使用中封装的组件

// 文档 (https://flowercloud.net/aff.php?aff=11050) 
import React from 'react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus, coyWithoutShadows, darcula } from 'react-syntax-highlighter/dist/esm/styles/prism';// 代码高亮主题风格

// vscDarkPlus vscode 暗色主题
// darcula  webstorm 暗色主题
// coyWithoutShadows 上面展示的效果

type tProps = {
  textContent: string;
  language: string;
  darkMode?: boolean;
}

const them = {
  dark: vscDarkPlus,
  light: coyWithoutShadows
};

const OmsSyntaxHighlight = (props: tProps) => {
  const { textContent, darkMode, language = 'txt' } = props;
  if (typeof darkMode === 'undefined') {
    them.light = darcula;
  }
  if (typeof darkMode === 'boolean') {
    them.light = coyWithoutShadows;
  }
  return (
    <SyntaxHighlighter
      showLineNumbers={true} // 是否展示左侧行数
      lineNumberStyle={{ color: '#ddd', fontSize: 10 }} // 左侧行数的样式
      style={darkMode ? them.dark : them.light}  // 主题风格
      language={language}  // 需要语言类型 如css, jsx , javascript 等
      PreTag='div'  
    >
      {String(textContent).replace(/\n$/, '')}
    </SyntaxHighlighter>
  );
};

export default OmsSyntaxHighlight;
import React from 'react';
import { OmsSyntaxHighlight } from 'xxxxx';

const textContent = 'console.log(1);'

const Demo = () => {
 return <OmsSyntaxHighlight textContent={textContent} language={javascript} darkMode />
}

可以根据需求实现二次封装达到想要的效果,比如在我的项目中我需要实现代码高亮的主题随我的项目主题改变实现亮暗主题的切换效果。
在这里插入图片描述
在这里插入图片描述
如果我没有传入darkMode这个参数,默认的就是webstorm的风格,官方提供了很多风格。感兴趣的话可以去这里查看
在这里插入图片描述

二、react-markdown的使用

// 文档 (https://flowercloud.net/aff.php?aff=11050) 
import React from 'react';
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus, coyWithoutShadows, darcula } from 'react-syntax-highlighter/dist/esm/styles/prism';

// darcula webstorm
// vscDarkPlus vscode暗色主题

type tProps = {
  textContent: string
  darkMode?: boolean; // markdown文本
}

const them = {
  dark: vscDarkPlus,
  light: coyWithoutShadows
};

const OmsViewMarkdown = (props: tProps) => {
  const { textContent, darkMode } = props;
  if (typeof darkMode === 'undefined') {
    them.light = darcula;
  }
  if (typeof darkMode === 'boolean') {
    them.light = coyWithoutShadows;
  }
  return (
    <ReactMarkdown
      components={{
        code({ node, inline, className, children, ...props }) {
          const match = /language-(\w+)/.exec(className || '');
          return !inline && match ? (
            <SyntaxHighlighter
              showLineNumbers={true}
              style={darkMode ? them.dark : them.light}
              language={match[1]}
              PreTag='div'
              {...props}
            >
              {String(children).replace(/\n$/, '')}
            </SyntaxHighlighter>
          ) : (
            <code className={className} {...props}>
              {children}
            </code>
          );
        }
      }}
    >
      {textContent}
    </ReactMarkdown>
  );
};

export default OmsViewMarkdown;

import React from 'react';
import { OmsViewMarkdown} from 'xxxxx';

const textContent = `
## 项目简介
本项目后端使用gin、gorm和ssh、sftp开发。旨在编写一个轻量,易用,多平台的运维项目。
前端使用react、typescript、vite构建。
现阶段目的是做一个阉割版的xshell并简单的实现ansible或者saltstack的部分功能。

### 目前已经实现的功能
1. 隧道, 类似ssh的-L和-R
2. cron任务和长进程的管理
3. ssh命令批量执行
4. 文件批量的上传 流式传输支持大文件
5. 基于sftp文件浏览器

### 查看后端代码请移步到 [oms](https://github.com/ssbeatty/oms)`;

const Demo = () => {
 return <OmsViewMarkdown textContent={textContent}  darkMode />
}

在这里插入图片描述

总结

以上就是两个库比较简单的使用方法,感兴趣的小伙伴可以在自己的项目中试一下。另外本文中的图片来自个人项目oms运维管理系统目前实现了文件浏览上传等功能。感兴趣的小伙伴可以看看👀github连接 gitee连接
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

### 如何在 React实现 Markdown 格式的预览功能 为了实现React 应用程序中显示 Markdown 文本并将其转换为 HTML 进行渲染,可以使用 `react-markdown` 组件。这使得开发者能够轻松集成 Markdown 解析能力到应用之中[^1]。 下面是一段基础示例代码展示了如何导入必要的模块以及创建一个简单的组件来进行 Markdown 的解析与展示: ```jsx import React from 'react'; import ReactDOM from 'react-dom/client'; import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; import { atomDark } from 'react-syntax-highlighter/dist/esm/styles/prism'; import RemarkMath from 'remark-math'; import RehypeKatex from 'rehype-katex'; // 导入 react-markdown 和其他依赖库 import { Markdown } from 'react-markdown'; const App = () => ( <Markdown remarkPlugins={[RemarkMath]} rehypePlugins={[RehypeKatex]} components={{ code({ inline, className, children, ...props }) { const match = /language-(\w+)/.exec(className || ''); return !inline && match ? ( <SyntaxHighlighter {...props} children={String(children).replace(/\n$/, '')} style={atomDark} language={match[1]} PreTag="div" /> ) : ( <code {...props} className={className}> {children} </code> ); }, }} > # 欢迎使用 React-Markdown! 下面是一个带有语法高亮的 JavaScript 代码片段: ```js console.log('Hello World'); ``` 并支持 LaTeX 数学表达式: $E=mc^2$ </Markdown> ); export default App; const rootElement = document.getElementById('root'); if (rootElement) { const root = ReactDOM.createRoot(rootElement); root.render(<App />); } ``` 上述例子不仅实现了基本的文字转义和链接处理等功能,还加入了对代码块着色的支持以及数学公式的正确渲染[^4]。 对于更复杂的需求,比如构建具备实时编辑特性的在线编辑器,则可以通过引入额外的状态管理逻辑来同步用户的输入变化,并即时更新视图中的 Markdown 预览效果[^3]。 #### 注意事项 - **安全性**: 当从不可信源获取 Markdown 数据时,请务必先对其进行净化以防止潜在的安全风险,例如跨站脚本攻击(XSS)[^2]。 - **性能考量**: 如果要处理大量的 Markdown 内容,建议采用分页或者懒加载等方式优化用户体验。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值