【发布时间】:2021-02-18 12:03:55
【问题描述】:
我有一个 scrollView 元素,如果用户向下或向上滚动,我想调用不同的回调函数
【问题讨论】:
我有一个 scrollView 元素,如果用户向下或向上滚动,我想调用不同的回调函数
【问题讨论】:
您可以使用onScroll 属性在用户滚动时收到通知。
为了达到您想要的效果,您只需要存储位置,如果有更新,请检查 y 位置的变化是正像素量(下)还是负像素量(上) .
作为一个功能性的 React 组件,它看起来像这样:
function MyComponent() {
// we use a ref here in order to store the value between rendering without triggering an update (like useState would)
const scrollYRef = useRef(0)
return (
<ScrollView
onScroll={(event) => {
// 0 means the top of the screen, 100 would be scrolled 100px down
const currentYPosition = event.nativeEvent.contentOffset.y
const oldPosition = scrollYRef.current
if(oldPosition < currentYPosition) {
// we scrolled down
} else {
// we scrolled up
}
// save the current position for the next onScroll event
scrollYRef.current = currentYPosition
}}
....
/>
)
}
【讨论】: