useScrollToTop
可滚动组件的预期原生行为是响应导航中的事件,当点击活动选项卡时,导航将滚动到顶部,就像你对原生选项卡栏所期望的那样。
¥The expected native behavior of scrollable components is to respond to events from navigation that will scroll to top when tapping on the active tab as you would expect from native tab bars.
为了实现它,我们导出 useScrollToTop
,它接受可滚动组件的引用(例如 ScrollView
或 FlatList
)。
¥In order to achieve it we export useScrollToTop
which accept ref to scrollable component (e,g. ScrollView
or FlatList
).
示例:
¥Example:
- Static
- Dynamic
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>
);
}
与类组件一起使用
¥Using with class component
你可以将类组件封装在函数组件中以使用钩子:
¥You can wrap your class component in a function component to use the 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} />;
}
提供滚动偏移
¥Providing scroll offset
如果你需要偏移滚动位置,你可以封装和装饰传递的引用:
¥If you require offset to scroll position you can wrap and decorate passed reference:
- Static
- Dynamic
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>
);
}