跳到主要内容
版本: 7.x

useScrollToTop

可滚动组件的预期原生行为是响应来自导航的事件,当点击活动标签时,滚动到顶部,就像您从原生标签栏期望的那样。

为了实现这一点,我们导出了 useScrollToTop,它接受可滚动组件的 ref(例如 ScrollViewFlatList)。

示例

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>
);
}
Snack 上尝试

与类组件一起使用

你可以将你的类组件包装在一个函数组件中来使用 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} />;
}

提供滚动偏移量

如果你需要滚动位置的偏移量,你可以包装和修饰传递的 ref

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>
);
}
Snack 上尝试