第2世界
发布于 2023-05-16 / 9 阅读 / 0 评论 / 0 点赞

react hooks两个表格同步滚动

在开发electron应用中,需要左右两个区域同步滚动,在网上找到下面这个解决思路记录一下。

原文:https://www.cnblogs.com/zihang-cheng/p/16492198.html

import "./styles.css";
import { useRef } from "react";

export default function App() {
  const firstDivRef = useRef();
  const secondDivRef = useRef();

  const handleScrollFirst = (scroll) => {
    secondDivRef.current.scrollTop = scroll.target.scrollTop;
  };

  const handleScrollSecond = (scroll) => {
    firstDivRef.current.scrollTop = scroll.target.scrollTop;
  };

  return (
    <div
      className="App"
      style={{
        display: "flex",
        height: "500px",
        overflow: "hidden",
        border: "1px solid black"
      }}
    >
      <div
        onScroll={handleScrollFirst}
        ref={firstDivRef}
        style={{
          height: "100%",
          overflow: "scroll",
          backgroundColor: "#FFDAB9"
        }}
      >
        <div style={{ height: 5000, width: 300 }}>
          The first div (or it can be tbody of a table and etc.)
          {[...new Array(1000)].map((_, index) => {
            const isEven = index % 2 === 0;
            return (
              <div style={{ backgroundColor: isEven ? "#FFFFE0    " : "#FFDAB9" }}>
                {index}
              </div>
            );
          })}
        </div>
      </div>

      <div
        onScroll={handleScrollSecond}
        ref={secondDivRef}
        style={{
          height: "100%",
          overflow: "scroll",
          backgroundColor: "#EEE8AA"
        }}
      >
        <div style={{ height: 5000, width: 200 }}>
          The second div
          {[...new Array(1000)].map((_, index) => {
            const isEven = index % 2 === 0;
            return (
              <div style={{ backgroundColor: isEven ? "#FFFFE0    " : "#FFDAB9" }}>
                {index}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}


评论