# 問題

GSAP target .page-title not found. https://gsap.com Error Component Stack
at BlogPostList (blog-post-list.tsx:15:19)
at div (<anonymous>)
at div (<anonymous

以上這類錯誤發生的主因是 GSAP 嘗試在 DOM 元素完全渲染到頁面之前對其進行動畫處理

原本會導致錯誤發生的程式碼:

useGSAP(() => {
    // 頁面載入時的動畫
    const tl = gsap.timeline();
    tl.fromTo(".page-title",
     { y: -20, opacity: 0 },
     { y: 0, opacity: 1, duration: 0.6 }).
    fromTo(".filter-container",
     { y: -10, opacity: 0 },
     { y: 0, opacity: 1, duration: 0.5 }, "-=0.3");
}, []);
return(
    <h1 className='page-title text-4xl font-bold mb-8'>最新文章</h1>
    ...
    <div className='filter-container mb-8 flex flex-col items-center'>
)

# 解決方法

改使用 React 的 useRef 來直接引用 DOM 元素,而不是通過類名選擇器查找它們:

const titleRef = useRef(null);
const filterRef = useRef(null);

useGSAP(() => {
 // 頁面載入時的動畫
 // 確保DOM元素已經渲染
 if (titleRef.current && filterRef.current) {
  const tl = gsap.timeline();
  tl.fromTo(titleRef.current, 
         { y: -20, opacity: 0 }, 
         { y: 0, opacity: 1, duration: 0.6 }).
        fromTo(filterRef.current, 
         { y: -10, opacity: 0 }, 
         { y: 0, opacity: 1, duration: 0.5 }, "-=0.3");
 }
}, []);

return(
    <h1 ref={titleRef} className='text-4xl font-bold mb-8'>最新文章</h1>
    ...
    <div ref={filterRef} className='mb-8 flex flex-col items-center'>
)

# 為什麼改用 useRef 就可以解決 GSAP 問題?

原因:

  1. 直接引用 vs 搜尋:
    • 不用 useRef 時:GSAP 使用 .page-title 去整個頁面「搜尋」這個元素
    • 用 useRef 後:GSAP 拿到的是元素的「直接引用」(就像有人直接牽著你的手帶你去目的地)
  2. 時間問題:
    • 沒用 useRef:GSAP 可能在元素還沒出現時就開始搜尋
    • 用 useRef:React 確保 ref.current 只有在元素實際存在時才會有值

重點就是 useRef 在需要直接訪問 DOM 元素的情況下是最好的選擇,因為它能確保你獲得的是元素的直接引用,而不是依賴於類名選擇器進行搜尋。這樣可以避免在元素尚未渲染時就嘗試對其進行動畫處理的問題。

請我喝[茶]~( ̄▽ ̄)~*

Young 微信支付

微信支付

Young 支付寶

支付寶