跳至主要內容
版本:6.x

useScrollToTop

捲動元件預期的原生行為是回應導覽事件,在輕觸活耀索引標籤時捲動至頂端,就像您對原生索引標籤列預期的那樣。

為達成此目標,我們匯出了 useScrollToTop 它接受捲動元件的參考(例如 ScrollViewFlatList)。

範例

import * as React from 'react';
import { ScrollView } from 'react-native';
import { useScrollToTop } from '@react-navigation/native';

function Albums() {
const ref = React.useRef(null);

useScrollToTop(ref);

return <ScrollView ref={ref}>{/* content */}</ScrollView>;
}

搭配類別元件使用

您可以將類別元件包覆在函式元件中以使用 Hook

class Albums extends React.Component {
render() {
return <ScrollView ref={this.props.scrollRef}>{/* content */}</ScrollView>;
}
}

// Wrap and export
export default function (props) {
const ref = React.useRef(null);

useScrollToTop(ref);

return <Albums {...props} scrollRef={ref} />;
}

提供捲動偏移

如果您需要偏移捲動位置,您可以包覆並設定傳遞的參考

import * as React from 'react';
import { ScrollView } from 'react-native';
import { useScrollToTop } from '@react-navigation/native';

function Albums() {
const ref = React.useRef(null);

useScrollToTop(
React.useRef({
scrollToTop: () => ref.current?.scrollTo({ y: 100 }),
})
);

return <ScrollView ref={ref}>{/* content */}</ScrollView>;
}