【问题标题】:How can I call event scrollView scrolls up or down in React Native? [closed]如何在 React Native 中调用事件 scrollView 向上或向下滚动? [关闭]
【发布时间】:2021-02-18 12:03:55
【问题描述】:

我有一个 scrollView 元素,如果用户向下或向上滚动,我想调用不同的回调函数

【问题讨论】:

    标签: react-native scrollview


    【解决方案1】:

    您可以使用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
          }}
          ....
        />
      )
    }
    
    

    【讨论】:

      猜你喜欢
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多