useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内持续存在。
日常开发中,可能会遇到:动态的创建 ref 引用。比如根据后台数据,去动态生成 html 元素,以及绑定事件。
根据 useRef 的定义,初始化时可以将参数值定义为数组或者对象,然后动态添加元素引用。
示例,使用 ref={el => { domRefs.current[index] = el }} :
// 初始化为数组
const domRefs = useRef([])
// 初始化为对象
// const domRefs = useRef({})
import { useRef } from 'react'
const Index = () => {
const domRefs = useRef([])
return (
<ul>
{
new Array(10).fill(0).map((item, index) =>
<li
key={index}
style={{
height: 20,
background: '#ccc',
margin: 10
}}
ref={el => { domRefs.current[index] = el }}
onClick={() => { console.log(domRefs, domRefs.current[index]) }}
>
{index + 1}
</li>
)
}
</ul>
)
}