如何在 React Native 中调用事件 scrollView 向上或向下滚动?
How can I call event scrollView scrolls up or down in React Native?
我有一个 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
}}
....
/>
)
}
我有一个 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
}}
....
/>
)
}