React子组件链接正常但标题、描述文本无法渲染问题求助
问题分析与解决方案
你的核心问题是子组件中列表项初始设置了opacity-0,但GSAP动画未正确触发将其改为1,导致文本视觉上被隐藏(链接功能正常是因为a标签本身可点击,只是看不见)。具体原因和修复步骤如下:
1. 未正确绑定元素到Ref
子组件中声明了itemsRef,但没有将每个<li>元素挂载到ref数组里,导致GSAP找不到要动画的元素,列表项一直保持opacity-0状态。
2. GSAP动画写法错误
在forEach循环中单独给每个元素设置动画时,stagger参数不会生效,应该直接对整个元素数组应用动画,让GSAP统一处理 stagger 逻辑。
修改后的子组件代码
"use client"; import React, { useRef, useEffect } from "react"; import { gsap } from "gsap"; import { MdArrowOutward } from "react-icons/md"; type ContentListProps = { items: { title: string; description: string; link: string }[]; viewMoreText: string; }; export default function ContentList({ items, viewMoreText = "Read More", }: ContentListProps) { const itemsRef = useRef<HTMLLIElement[]>([]); // 绑定ref到每个li元素 const setItemRef = (el: HTMLLIElement, index: number) => { if (el) { itemsRef.current[index] = el; } }; useEffect(() => { // 确保ref数组元素数量与items一致再执行动画 if (itemsRef.current.length === items.length) { gsap.fromTo( itemsRef.current, { opacity: 0, y: 20 }, { opacity: 1, y: 0, duration: 1.3, ease: "elastic.out(1,0.3)", stagger: 0.2 // 现在stagger会正确应用到整个元素数组 } ); } }, [items]); return ( <ul className="grid border-b border-b-slate-100"> {items.map((item, index) => ( <li key={index} className="list-item opacity-0" ref={(el) => setItemRef(el as HTMLLIElement, index)} // 绑定ref到对应元素 > <a href={item.link} className="flex flex-col justify-between border-t border-t-slate-100 py-10 text-slate-200 md:flex-row "> <div className="flex flex-col"> <span className="text-3xl font-bold">{item.title}</span> <p className="text-lg text-gray-500">{item.description}</p> </div> <span className="ml-auto flex items-center gap-2 text-xl font-medium md:ml-0"> {viewMoreText} <MdArrowOutward /> </span> </a> </li> ))} </ul> ); }
额外检查点
- 确认页面背景与文本颜色对比度:如果背景是浅色,
text-slate-200和text-gray-500可能辨识度低,可临时改成text-black测试是否显示。 - 验证父组件传递的
projects数组:确保每个对象的title和description字段确实有有效值(你的示例代码中是正常的)。
内容的提问来源于stack exchange,提问作者Akshey Gupta
相关产品推荐
相关产品推荐

