react mackDowan 渲染文本,图片,视频

需要安装:react-markdown;remark-gfm

"react-markdown": "^9.0.1",

"remark-gfm": "^4.0.0",

TypeScript 复制代码
import { useEffect, useState } from 'react';
import ReactMarkdown, { Components } from 'react-markdown';

function checkMediaType(url: string | URL) {
  // 创建URL对象
  let link = new URL(url);

  // 获取路径部分(去除参数)
  let path = link.pathname;

  // 获取路径的最后一个点之后的内容作为文件扩展名
  
  let extension = path?.split('.')?.pop()?.toLowerCase();

  // 声明支持的图片和视频文件扩展名
  const imageExtensions = ['jpg', 'jpeg', 'gif', 'png'];
  const videoExtensions = ['mp4', 'wmv', 'avi', 'mov'];

  // 判断文件扩展名是否在图片扩展名数组中
  if (extension && imageExtensions.includes(extension)) {
    return 'image';
  }

  // 判断文件扩展名是否在视频扩展名数组中
  if (extension && videoExtensions.includes(extension)) {
    return 'video';
  }

  // 扩展名不在图片或视频数组中,返回null表示无法确定媒体类型
  return null;
}

const components: Components = {
  a({ children, node }) {
    if (
      node &&
      typeof node.properties?.href === 'string' &&
      checkMediaType(node.properties.href)
    ) {
      return (
        <video
          style={{ width: 200, height: 200 }}
          controls
          src={node.properties.href}
        ></video>
      );
    }
    return <a {...node?.properties}>{children}</a>;
  },
};

function AIMarkdown() {
  const [content, setContent] = useState('');
  const content1 = `你好我是markDown下面会展示图片及视频:

1. 观看操作视频:[演示(1)](https://www.w3schools.com/html/mov_bbb.mp4)
2. 查看详细步骤图解:![image.png](https://gw.alipayobjects.com/zos/bmw-prod/598d14af-4f1c-497d-b579-5ac42cd4dd1f/k7bjua9c_w132_h130.png)

这些资料将指导您完成通讯录的添加人员等操作。`;
  useEffect(() => {
    let index = 0;
    const i = setInterval(() => {
      if (index < content1.length) {
        setContent((v) => {
          return v + content1[index];
        });
        index++;
      } else {
        clearInterval(i);
      }
    }, 10);
    return () => clearInterval(i);
  }, []);

  return <ReactMarkdown components={components}>{content || ''}</ReactMarkdown>;
}

export default AIMarkdown;

使用

TypeScript 复制代码
//引入文件
import AIMarkdown from './MessageAI';

.
.
.
.


<div className={style.canter}>
   <AIMarkdown />
</div>
相关推荐
Thera77721 小时前
C++ 高性能时间轮定时器:从单例设计到 Linux timerfd 深度优化
linux·开发语言·c++
yy我不解释21 小时前
关于comfyui的mmaudio音频生成插件时时间不一致问题(一)
python·ai作画·音视频·comfyui
炘爚21 小时前
C语言(文件操作)
c语言·开发语言
阿蒙Amon1 天前
C#常用类库-详解SerialPort
开发语言·c#
凸头1 天前
CompletableFuture 与 Future 对比与实战示例
java·开发语言
wuqingshun3141591 天前
线程安全需要保证几个基本特征
java·开发语言·jvm
Moksha2621 天前
5G、VoNR基本概念
开发语言·5g·php
jzlhll1231 天前
kotlin Flow first() last()总结
开发语言·前端·kotlin
W.D.小糊涂1 天前
gpu服务器安装windows+ubuntu24.04双系统
c语言·开发语言·数据库
用头发抵命1 天前
Vue 3 中优雅地集成 Video.js 播放器:从组件封装到功能定制
开发语言·javascript·ecmascript