【问题标题】:IonContent will not trigger scroll events if assigned a ref如果分配了 ref,IonContent 将不会触发滚动事件
【发布时间】:2021-03-19 00:47:14
【问题描述】:

我今天遇到了最奇怪的问题。我的代码(大部分已被删除)基本上包括以下内容:

const Element: React.FC<any> = (props: any) => {
  const scrollRef = React.useRef<any>(null);

  .
  .
  .

  const rescrollTrigger = () => {
    setTimeout(() => { /* Retry for 10 seconds to scroll the content to match the stored value, unless the user has scrolled since then */
      const cb = (tries: number) => {
        if (tries > 100)
          return;

        if (!scrollRef.current) {
          setTimeout(cb, 100, [Number(tries) + 1]);
          return;
        }
        
        scrollRef.current.getScrollElement().then((element: any) => {
          var scrollHeight: any = window.sessionStorage.getItem(thisPath + "/scrollheight");
          var scrollTop: any = window.sessionStorage.getItem(thisPath + "/scrolltop");

          if (!scrollHeight || !scrollTop)
            return;

          scrollHeight = +scrollHeight;
          scrollTop = +scrollTop;

          if (element.scrollHeight == scrollHeight)
            scrollRef.current.scrollToPoint(0, scrollTop);
          else
            setTimeout(cb, 100, [Number(tries) + 1]);
        }).catch(() => {
          setTimeout(cb, 100, [Number(tries) + 1]);
        })
      };

      window.requestAnimationFrame(() => {
        cb(1);
      });
    });
  };

  const saveScrollPosition = () => {
    console.log("saveScrollPosition", scrollRef.current);
    try {
      scrollRef.current.getScrollElement().then((element: any) => { 
        console.log("Saving scroll position");
        window.sessionStorage.setItem(thisPath + "/scrolltop", String(element.scrollTop));
        window.sessionStorage.setItem(thisPath + "/scrollheight", String(element.scrollHeight));
      });
    } catch (err) {console.log("Error saving scroll position", err)}
  };

  return (
    <IonPage>
      <IonContent fullscreen ref={scrollRef} scrollEvents={true} onIonScrollEnd={e => saveScrollPosition()}>

      .
      .
      .
}

我只是想为内容实例创建一个引用(在挂钩中),以便我可以根据需要保存和重置滚动位置。

此代码运行良好,但由于某种原因,如果在内容元素上设置了 ref,则停止触发任何滚动事件。我试过onIonScrollonIonScrollEnd。如果设置了 ref,则两者都不起作用。删除ref={scrollRef} 开始触发滚动事件。我正在使用 Ionic 6.12.2,并且最近刚刚从以前的版本升级(我不知道它是什么)。

所以我的问题是:这是 Ionic 中的错误吗?或者如果没有,应该如何修复代码?我尝试不设置 ref 并仅使用从滚动事件返回的目标,这允许我保存位置,但它不保留能够稍后重置滚动位置的引用。

【问题讨论】:

    标签: reactjs ionic-framework scroll react-hooks


    【解决方案1】:

    这看起来像一个离子错误。 Ionic 6.12.3 允许使用ref 触发事件,并且该行为不可重现。

    【讨论】:

      猜你喜欢
      • 2020-05-03
      • 2019-04-10
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      相关资源
      最近更新 更多