React网站集成SVG 3D标签云插件求助(附代码)
在React项目里搞SVG 3D标签云(放网页右侧)
1. 先装依赖
直接用3d-tag-cloud这个库就行,先安装:
npm install 3d-tag-cloud --save
2. 封装成React组件
新建个TagCloud.js文件,把原生库的逻辑包成React组件:
import React, { useEffect, useRef } from 'react'; import TagCloud from '3d-tag-cloud'; const SVGTagCloud = () => { const cloudContainer = useRef(null); useEffect(() => { if (!cloudContainer.current) return; // 准备要显示的标签,自己按需添加 const tags = [ { name: 'React', link: '#react' }, { name: 'JavaScript', link: '#js' }, { name: 'CSS', link: '#css' }, { name: 'SVG', link: '#svg' }, { name: '前端开发', link: '#frontend' } ]; // 初始化标签云 const tagCloud = TagCloud(cloudContainer.current, { radius: 200, // 球体大小,数值越大球越大 maxSpeed: 'normal', // 旋转速度:slow/normal/fast initSpeed: 'normal', direction: 135, // 初始旋转方向的角度 keep: true // 鼠标移开后要不要继续转 }); // 把标签一个个加进去 tags.forEach(item => { const link = document.createElement('a'); link.href = item.link; link.target = '_blank'; link.innerText = item.name; tagCloud.addNode(link); }); // 组件卸载时清理资源 return () => tagCloud.destroy(); }, []); return ( <div ref={cloudContainer} style={{ position: 'fixed', right: '20px', top: '50%', transform: 'translateY(-50%)', width: '400px', height: '400px' }} /> ); }; export default SVGTagCloud;
3. 加到主页面里
在你的index.js里引入这个组件:
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.scss'; import SVGTagCloud from './TagCloud'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <div className="app"> {/* 这里放你原来的页面内容 */} <SVGTagCloud /> </div> </React.StrictMode> );
4. 调整标签样式(index.scss)
想改标签的字体、颜色这些,就在index.scss里加:
/* 3D标签云的标签样式 */ #tag-cloud a { color: #333; text-decoration: none; font-size: 16px; } #tag-cloud a:hover { color: #007bff; text-decoration: underline; }
额外说明
如果目标效果和这个库的表现不一样,你可以把你提供的script.js里的原生逻辑,放到组件的useEffect里执行——核心就是等组件挂载完成后再初始化标签云。要是需要用React路由跳转,把a标签换成React Router的Link组件,调整下添加节点的逻辑就可以。
内容的提问来源于stack exchange,提问作者deandrehaijiel
相关产品推荐
相关产品推荐

