useScrollToTop
可滚动组件的预期原生行为是响应来自导航的事件,当点击活动标签时,滚动到顶部,就像您从原生标签栏期望的那样。
为了实现这一点,我们导出了 useScrollToTop
,它接受可滚动组件的 ref(例如 ScrollView
或 FlatList
)。
示例
- 静态
- 动态
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>
);
}
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} />;
}
提供滚动偏移量
如果你需要滚动位置的偏移量,你可以包装和修饰传递的 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>
);
}
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>
);
}