0

我正在尝试使用提供的scrollToOffset和。但是,我使用的 ref 在使用时始终未定义。scrollToIndexSectionListSectionListref.current

在我的类组件中,我有以下内容:

private sectionListRef: any;

constructor(props: SampleScreenProps) {
    super(props);
    this.sectionListRef = null;
}

componentDidMount = (): void => {
    setTimeout(() => this.scrollToSection(), 2000);
};

scrollToSection = (): void => {
    
    // do some calculations to get the itemIndex and sectionIndex to scroll to

    this.sectionListRef.scrollToLocation({
        animated: false,
        itemIndex,
        sectionIndex,
        viewPosition: 0.5
    }); // this fails if the list is huge and the indices are far from the initial render location, and so moves on to onScrollToIndexFailed 
};

onScrollToIndexFailed = (error) => {
    // this.sectionListRef.current is always undefined in this function

    this.sectionListRef.current?.scrollToOffset({
        offset: error.averageItemLength * error.index,
        animated: true
    });
    setTimeout(() => {
        if (this.state.dataSet.length !== 0 && this.sectionListRef !== null) {
            this.sectionListRef.current?.scrollToIndex({ index: error.index, animated: true });
        }
    }, 10);
};

最后,这是SectionList它本身:

<SectionList
    inverted
    ref={(ref) => {
        this.sectionListRef = ref;
    }}
    sections={mappedSections}
    renderItem={this.renderItem}
    renderSectionFooter={this.renderSectionFooter}
    keyExtractor={(item, index) => index.toString()}
    keyboardShouldPersistTaps="never"
    keyboardDismissMode="on-drag"
    bounces={false}
    initialNumToRender={20}
    onScrollToIndexFailed={this.onScrollToIndexFailed}
/>

这是什么原因?

编辑:我尝试this.sectionListRef = React.createRef()在构造函数中做,但结果相同。

我知道scrollToOffset是 的一部分SectionList,但其他两个滚动功能是底层虚拟化列表的一部分,但据我所知,它应该仍然可以正常工作。

4

0 回答 0