【问题标题】:How can I synchronize the "scrollLeft" property of 2 divs while scrolling horizontally within a react component?如何在反应组件中水平滚动时同步 2 个 div 的“scrollLeft”属性?
【发布时间】:2021-05-26 13:34:30
【问题描述】:

我想在反应组件中“同步”2 个“div”的 x 位置。最终,我希望有一个始终可见的表格标题和一个可以垂直滚动的表格。该表头和该表的水平偏移量应该保持“同步”。

“onScroll”事件触发。但是,在我的函数reactToScrolling 中更改属性“offsetX”的“状态”对我的“div”没有影响(据我所知)。我可以做些什么来完成这项工作?

const { useState } = require('react');

const MainComponent = () => {
const [ offsetX, setOffsetX ] = useState(0);

  function reactToScrolling(e) {
    console.log(e.target.scrollLeft);
    setOffsetX(e.target.scrollLeft);
  }
  
  return (
    <>
      <div style={{ height:'200pt', width:'800pt', overflow:'scroll'}} onScroll={reactToScrolling}>
        <div style={{ height:'600pt', width:'1600pt', backgroundColor:'red' }} scrollLeft={offsetX}>
          ...
        </div>
      </div>
      <div style={{ height:'200pt', width:'800pt', overflow:'scroll'}} onScroll={reactToScrolling}>
        <div style={{ height:'600pt', width:'1600pt', backgroundColor:'blue' }} scrollLeft={offsetX}>
          ...
        </div>
      </div>
    </>
  )
};

export default MainComponent;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    最终,我自己找到了解决方案。如果使用useRef 而不是useState,它会完美运行。当滚动事件触发时,使用useRef 创建的引用将div1scrollLeft 属性设置为div2scrollLeft 属性的值。

    const { useRef } = require('react');
    
    const MainComponent = () => {
      const div1 = useRef(null);
      const div2 = useRef(null);
    
      const onScroll = () => {
        div1.current.scrollLeft = div2.current.scrollLeft;
      }
    
      return (
        <>
        <div ref={div1} style={{ height:'200pt', width:'800pt', overflow:'scroll'}} onScroll={onScroll}>
          <div style={{ height:'600pt', width:'1600pt', backgroundColor:'lightgray' }}>
            ...
      </div>
        </div>
        <div ref={div2} style={{ height:'200pt', width:'800pt', overflow:'scroll'}} onScroll={onScroll}>
          <div style={{ height:'600pt', width:'1600pt', backgroundColor:'lightgray' }}>
            ...
          </div>
        </div>
      </>
      )
    };
    
    export default MainComponent;
    

    【讨论】:

      【解决方案2】:

      谢谢,这对我帮助很大。

      最后,我刚刚为顶部 div 添加了另一个函数,以便它也可以自己处理滚动。

      const onScrollTop = () => {
      div2.current.scrollLeft = div1.current.scrollLeft;
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-13
        • 1970-01-01
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 2021-12-06
        • 2017-05-15
        • 1970-01-01
        相关资源
        最近更新 更多