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

React Native SectionList 调用scrollToLocation指定itemIndex为0时始终滚动至首个分区第一项的问题求助

React Native SectionList 调用scrollToLocation指定itemIndex为0时始终滚动至首个分区第一项的问题求助

大家好,我最近在React Native项目里用SectionList做多分区列表展示,需要通过scrollToLocation方法实现编程式滚动到指定的分区和子项,但在iOS上碰到了一个奇怪的问题:

当我调用scrollToLocation时,如果传入的itemIndex是0,不管我指定的sectionIndex是多少,列表都会直接滚到第一个分区的第一个子项;但只要itemIndex大于0,滚动就完全正常,能精准定位到对应的分区和子项上。

我已经确认了SectionList的ref是正常获取的,sections数据结构也没问题,实在找不到问题出在哪,麻烦各位帮忙看看!

下面是我简化后的复现代码:

import React, { useRef } from 'react';
import {
  SectionList,
  View,
  Text,
  Button,
  StyleSheet,
  StatusBar,
} from 'react-native';

const App = () => {
  const sectionListRef = useRef<SectionList>(null);

  const sections = Array.from({ length: 10 }, (_, sectionIndex) => ({
    title: `Section ${sectionIndex + 1}`,
    data: Array.from(
      { length: 30 },
      (_, itemIndex) => `Item ${itemIndex + 1}`
    ),
  }));

  // 测试滚动到指定分区的第0项
  const scrollToTestItem = () => {
    // 比如这里想滚到第5个分区的第0项,但实际会滚到第1个分区的第0项
    sectionListRef.current?.scrollToLocation({
      sectionIndex: 4,
      itemIndex: 0,
      animated: true,
    });
  };

  return (
    <View style={styles.container}>
      <StatusBar barStyle="dark-content" />
      <Button title="滚动到第5分区第0项" onPress={scrollToTestItem} />
      <SectionList
        ref={sectionListRef}
        sections={sections}
        keyExtractor={(item, index) => item + index}
        renderItem={({ item }) => (
          <View style={styles.item}>
            <Text style={styles.itemText}>{item}</Text>
          </View>
        )}
        renderSectionHeader={({ section }) => (
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionHeaderText}>{section.title}</Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight,
  },
  sectionHeader: {
    padding: 12,
    backgroundColor: '#f0f0f0',
  },
  sectionHeaderText: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  item: {
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  itemText: {
    fontSize: 14,
  },
});

export default App;

我试过调整scrollToLocation的其他参数,比如viewPosition或者viewOffset,但都没解决这个问题。有没有朋友碰到过类似的情况?或者能帮我分析下可能的原因?

备注:内容来源于stack exchange,提问作者Md. Ibene Anas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 11:15:32