You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ScrollView嵌套FlatList时,点击按钮滚动到指定位置的实现方案

解决方案

你的核心问题是垂直ScrollView误用了横向滚动的x参数,且未正确获取每个列表项的垂直位置,导致滚动失效。以下是具体实现步骤:

1. 存储每个子项的Ref

创建ref数组保存ScrollView内每个动态生成的View节点:

const itemRefs = useRef([]);

渲染列表时给每个View绑定ref,并补全必要的key属性:

<ScrollView ref={verticalRef}>
  {data.map((item, index) => (
    <View 
      key={index}
      ref={el => itemRefs.current[index] = el}
    >
      <Text style={styles.title}>{item.title}</Text>
      <View>
        <FlatList
          data={item.data}
          numColumns={2}
          renderItem={thitem}
        />
      </View>
    </View>
  ))}
</ScrollView>

2. 获取每个子项的垂直位置

使用measure方法获取每个子项的y坐标,存入状态:

import { useState, useEffect } from 'react';

const [itemPositions, setItemPositions] = useState([]);

useEffect(() => {
  const positions = [];
  itemRefs.current.forEach((ref, index) => {
    if (ref) {
      ref.measure((_x, y, _width, _height, _pageX, _pageY) => {
        positions[index] = y;
      });
    }
  });
  setItemPositions(positions);
}, [data]);

3. 修改滚动函数

将原函数的x参数改为垂直滚动的y,并使用对应索引的垂直位置:

const scrollToActiveIndex = (index) => {
  setActiveIndex(index);
  if (verticalRef.current && itemPositions[index] !== undefined) {
    verticalRef.current.scrollTo({
      y: itemPositions[index],
      animated: true
    });
  }
};

额外注意点

  • 若FlatList高度异常,可给其父View添加style={{flex: 1}},确保FlatList能正确渲染并被测量高度
  • 数据频繁更新时,可使用useCallback优化滚动函数,避免不必要的渲染

内容的提问来源于stack exchange,提问作者Bro Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:45:44