当前位置:网站首页>useRef 创建动态引用
useRef 创建动态引用
2022-07-24 05:17:00 【梅花三】
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>
)
}
边栏推荐
猜你喜欢
随机推荐
求网络的flops
用C语言写出三子棋
Opengl模拟现实生活中,球掉到地面上再弹起来的过程,在屏幕上绘制一个球,球从上往下掉,碰到地面,再弹起来。
解决:控制台使用nvm控制node版本时出现exit status 1与exit status 145
Implementation and comparison of nine sorting (ten thousand words summary)
SSM integration
总结Browser对象
输入10个人的名字,按从大到小排序输出
c2-随机产生函数种子seed、numpy.random.seed()、tf.random.set_seed学习+转载整理
数组_01forEach中的return
C语言进阶篇 二. 指针
Add, delete, modify and check JDBC
一步一步带你学C(其二)
你真的知道判断语句吗?
Neo4j修改标签名
special effects - 鼠标点击,出现烟花炸裂效果
LaTeX学习笔记(一)——安装配置
Learn AI linear regression from Li Mu. The code implementation from scratch is super detailed
Create and delete databases using databases
在屏幕上绘制一个正方形,用ice.bmp对正方形做纹理映射;在正方形后绘制一个黄色的茶壶,假设正方形是透明的,绘制茶壶与正方形的混合效果;通过A,D,W和K按键调整茶壶在X轴和Y轴的位置,具体如下









