Skip to content

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