React TypeScript中如何创建Ref数组实现多区块滚动定位
React 多区块滚动定位:用Ref数组实现点击跳转
要实现多个区块的滚动定位,你可以按以下步骤改造代码:
1. 初始化Ref数组
用useRef创建一个空数组来存储每个区块的DOM引用:
const chapterRefs = React.useRef([]);
2. 编写通用滚动函数
创建一个接收索引的函数,根据索引找到对应区块的Ref并执行滚动:
const scrollToChapter = (index) => { if (chapterRefs.current[index]) { chapterRefs.current[index].scrollIntoView({ behavior: 'smooth', // 可选:开启平滑滚动 block: 'start' // 可选:滚动到区块顶部 }); } };
3. 给每个区块绑定Ref
使用回调Ref的方式,把每个区块的DOM元素存入Ref数组:
如果是基于列表数据渲染区块:
const chapters = ['123', '234', '345']; {chapters.map((content, index) => ( <div key={index} ref={el => chapterRefs.current[index] = el} className={styles.chapter} > <b>{content}</b> </div> ))}
如果是手动编写多个区块:
<div ref={el => chapterRefs.current[0] = el} className={styles.chapter} > <b>123</b> </div> <div ref={el => chapterRefs.current[1] = el} className={styles.chapter} > <b>234</b> </div> <div ref={el => chapterRefs.current[2] = el} className={styles.chapter} > <b>345</b> </div>
4. 给按钮绑定对应滚动事件
每个按钮点击时传入对应区块的索引,触发滚动:
{chapters.map((_, index) => ( <div key={index} onClick={() => scrollToChapter(index)} className={styles.contentChapter} > 跳转到章节{index + 1} </div> ))}
关键说明
- 必须用回调Ref:直接赋值
ref={chapterRefs.current[index]}会导致React渲染时无法正确关联DOM元素,回调Ref能确保每个元素被存入数组对应位置。 scrollIntoView的配置项可按需调整,比如去掉behavior: 'smooth'就会瞬间滚动到目标位置。
内容的提问来源于stack exchange,提问作者CRAYS CRAYSOVICH
相关产品推荐
相关产品推荐

