TagCloud在Vercel部署后无法显示问题求助
TagCloud组件本地正常但Vercel部署后不显示的解决方案
核心问题
- 你将TagCloud的初始化逻辑放在了
useEffect的清理函数(return的函数)中,该函数仅在组件卸载或依赖项更新时执行,生产环境下组件挂载阶段不会触发初始化,导致组件无法渲染。本地开发环境因热重载机制可能偶然触发执行,造成“正常显示”的假象。 - CSS中
.tagcloud的display: absolute是错误属性,应为position: absolute,可能影响布局定位。
解决方案
- 将TagCloud初始化逻辑移到
useEffect的主回调中(组件挂载时执行) - 使用
useRef获取DOM元素,替代document.querySelector,避免元素选择错误 - 添加TagCloud实例的销毁逻辑,防止内存泄漏
- 修正CSS中的属性错误
修改后的代码
JSX代码
import TagCloud from "TagCloud"; import { useEffect, useRef } from "react"; import "./textphere.css"; export const text = [ "HTML", "CSS", "Tailwind", "Javascript", "Typescript", "NodeJS", "React", "Next JS", "Webpack", "Docker", "Babel", "Kubernetes", "ES6", "NoSQL", "SQL", "YAML", "SSR", "CSR", "SSG", "Stripe API", "REST API", "Graph QL", ] as string[]; function TextSphere() { const tagCloudRef = useRef<HTMLSpanElement>(null); const tagCloudInstanceRef = useRef<any>(null); useEffect(() => { const container = tagCloudRef.current; if (!container) return; const options = { radius: 300, maxSpeed: "normal", initSpeed: "normal", keep: true, }; // 初始化TagCloud并保存实例 tagCloudInstanceRef.current = TagCloud(container, text, options); // 卸载时销毁实例,防止内存泄漏 return () => { tagCloudInstanceRef.current?.destroy(); }; }, []); return ( <div> <div className="text-shpere"> <span ref={tagCloudRef} className="tagcloud"></span> </div> </div> ); } export default TextSphere;
CSS代码(修正属性错误)
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;600;700;800;900&display=swap'); /* container */ .text-shpere { padding-top: 20px; position: relative; top: 0; display: flex; justify-content: center; align-items: center; background: rgb(250 250 249 / var(--tw-bg-opacity)) } /* textsphere */ .tagcloud { position: absolute; /* 修正display为position */ top: 0; left: 0; font-family: 'Inter', sans-serif; } /* Change color of each text in sphere on hover */ .tagcloud--item { color: #f1c400; text-transform: uppercase; } .tagcloud--item:hover { color: #ff6347; } @media (min-width: 900px) { .text-shpere{ width: 80%; height: 70vh; } .tagcloud{ font-weight: 600; font-size: 1rem; letter-spacing: 0.0425em; right: 5rem } } @media (min-width: 1200px ){ .text-shpere{ padding-top: 10%; width: 100%; } .tagcloud{ font-size: 1rem; transform: scale(1); border-radius: 50%; line-height: 100px; } } @media (min-width: 1400px ){ .tagcloud{ font-size: 1.5rem; transform: scale(1.11); } } @media (min-width: 1530px ){ .tagcloud{ font-size: 1.7rem; transform: scale(1.15); margin-left: 80px; padding-top: 40px; } } @media (min-width: 1900px){ .tagcloud{ padding-top: 100px; } }
内容的提问来源于stack exchange,提问作者user123
相关产品推荐
相关产品推荐

