react hooks两个表格同步滚动
1 import "./styles.css"; 2 import { useRef } from "react"; 3 4 export default function App() { 5 const firstDivRef = useRef(); 6 const secondDivRef = useRef(); 7 8 const handleScrollFirst = (scroll) => { 9 secondDivRef.current.scrollTop = scroll.target.scrollTop; 10 }; 11 12 const handleScrollSecond = (scroll) => { 13 firstDivRef.current.scrollTop = scroll.target.scrollTop; 14 }; 15 16 return ( 17 <div 18 className="App" 19 style={{ 20 display: "flex", 21 height: "500px", 22 overflow: "hidden", 23 border: "1px solid black" 24 }} 25 > 26 <div 27 onScroll={handleScrollFirst} 28 ref={firstDivRef} 29 style={{ 30 height: "100%", 31 overflow: "scroll", 32 backgroundColor: "#FFDAB9" 33 }} 34 > 35 <div style={{ height: 5000, width: 300 }}> 36 The first div (or it can be tbody of a table and etc.) 37 {[...new Array(1000)].map((_, index) => { 38 const isEven = index % 2 === 0; 39 return ( 40 <div style={{ backgroundColor: isEven ? "#FFFFE0 " : "#FFDAB9" }}> 41 {index} 42 </div> 43 ); 44 })} 45 </div> 46 </div> 47 48 <div 49 onScroll={handleScrollSecond} 50 ref={secondDivRef} 51 style={{ 52 height: "100%", 53 overflow: "scroll", 54 backgroundColor: "#EEE8AA" 55 }} 56 > 57 <div style={{ height: 5000, width: 200 }}> 58 The second div 59 {[...new Array(1000)].map((_, index) => { 60 const isEven = index % 2 === 0; 61 return ( 62 <div style={{ backgroundColor: isEven ? "#FFFFE0 " : "#FFDAB9" }}> 63 {index} 64 </div> 65 ); 66 })} 67 </div> 68 </div> 69 </div> 70 ); 71 }