Skip to content
⚠️ This article was written in 2021. Some content may be outdated.

React 複合組件模式

React 複合組件模式在前端開發中的應用越來越廣泛。本文從實際項目出發,深入分析其核心原理和最佳實踐。

基礎用法

實際項目中的用法會更復雜一些:

javascript
import { useRef, useEffect, useState } from 'react'

function useIntersectionObserver(options = {}) {
  const [isVisible, setIsVisible] = useState(false)
  const ref = useRef(null)

  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      setIsVisible(entry.isIntersecting)
    }, { threshold: 0.1, ...options })
    const el = ref.current
    if (el) observer.observe(el)
    return () => { if (el) observer.unobserve(el) }
  }, [])

  return [ref, isVisible]
}

通過這種方式,代碼的可測試性和可擴展性都得到了提升。

進階用法

以下是一個完整的示例:

javascript
import { useRef, useEffect, useState } from 'react'

function useIntersectionObserver(options = {}) {
  const [isVisible, setIsVisible] = useState(false)
  const ref = useRef(null)

  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      setIsVisible(entry.isIntersecting)
    }, { threshold: 0.1, ...options })
    const el = ref.current
    if (el) observer.observe(el)
    return () => { if (el) observer.unobserve(el) }
  }, [])

  return [ref, isVisible]
}

注意邊界條件處理,這在生產環境中至關重要。

實戰案例

關鍵在於理解核心邏輯:

javascript
import { useRef, useEffect, useState } from 'react'

function useIntersectionObserver(options = {}) {
  const [isVisible, setIsVisible] = useState(false)
  const ref = useRef(null)

  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      setIsVisible(entry.isIntersecting)
    }, { threshold: 0.1, ...options })
    const el = ref.current
    if (el) observer.observe(el)
    return () => { if (el) observer.unobserve(el) }
  }, [])

  return [ref, isVisible]
}

性能優化需要結合具體場景,不是所有情況都需要過度優化。

性能優化

我們可以通過以下方式來改進:

javascript
import { useRef, useEffect, useState } from 'react'

function useIntersectionObserver(options = {}) {
  const [isVisible, setIsVisible] = useState(false)
  const ref = useRef(null)

  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      setIsVisible(entry.isIntersecting)
    }, { threshold: 0.1, ...options })
    const el = ref.current
    if (el) observer.observe(el)
    return () => { if (el) observer.unobserve(el) }
  }, [])

  return [ref, isVisible]
}

這套方案已經在線上穩定運行了半年以上,經過了實際驗證。

小結

  • 代碼示例僅供參考,需根據業務場景調整
  • React 複合組件模式不是銀彈,需要根據項目規模和技術棧選擇
  • 理解底層原理比記住 API 更重要
  • 生產環境使用前務必做好兼容性驗證
  • 團隊協作中約定和文檔比技術本身更重要

MIT Licensed