怎么样在 React Hooks 中批量使用 useRef ?

5,115 阅读1分钟

如题,想批量的在 Hooks 里面使用 useRef,该怎么做呢?

场景

比如之前的动画展示页面,有多个 Lottie 元素,每一个元素的启动/暂停需要调用方法才行,所以就需要用 ref,但是动画是批量渲染的,故需批量引用。

第一层

给一个 useRef 的数组,使用下标来进行引用。 核心代码如下:

export default function LottiePage() {
  const lotties = ['source_1', 'source_2']
  const useLottieRef = [useRef(null), useRef(null)]
  return (
    lotties.map((res, index)=>{
      return <LottieItemView ref={useLottieRef[index]} source={res}/> // 根据 index 使用数组中对应的 ref
    })
  )
}

第二层

有更好的方案吗?当然有!

封装需要批量使用的组件,让其内部自管理。

export default function LottiePage() {
  const lotties = ['source_1', 'source_2']
  return (
    lotties.map((res, index)=>{
      return <Item source={ress}/> 
    }))
}

// 组件抽离,这样可以实现多个同名Ref互相独立
function Item(props){
  const useLottieRef = useRef(null)
  return <LottieItemView ref={useLottieRef} source={props.source}/>
}

以上代码经过抽象简化。

各位有更好的第三层方案,可以讨论讨论!

Demo 示例

GitHub 地址: ExploreRN