需要安装:react-markdown;remark-gfm
"react-markdown": "^9.0.1",
"remark-gfm": "^4.0.0",
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 (<videostyle={{ width: 200, height: 200 }}controlssrc={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;
使用
//引入文件
import AIMarkdown from './MessageAI';.
.
.
.<div className={style.canter}><AIMarkdown />
</div>