Javascript 我如何同步“文件”;“向左滚动”;在react组件内水平滚动时2个div的属性?
我想“同步”react组件中2个“div”的x位置。最后,我希望有一个始终可见的表头和一个可以垂直滚动的表。该表标题和该表的水平偏移量应保持“同步” “onScroll”事件触发。但是,在我的函数Javascript 我如何同步“文件”;“向左滚动”;在react组件内水平滚动时2个div的属性?,javascript,reactjs,Javascript,Reactjs,我想“同步”react组件中2个“div”的x位置。最后,我希望有一个始终可见的表头和一个可以垂直滚动的表。该表标题和该表的水平偏移量应保持“同步” “onScroll”事件触发。但是,在我的函数reactoscrolling中更改属性“offsetX”的“状态”对我的“divs”没有影响(据我所见)。我能做些什么来让它工作 const { useState } = require('react'); const MainComponent = () => { const [ offse
reactoscrolling
中更改属性“offsetX”的“状态”对我的“divs”没有影响(据我所见)。我能做些什么来让它工作
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;
const{useState}=require('react');
常量MainComponent=()=>{
const[offsetX,setOffsetX]=useState(0);
函数反作用克隆(e){
console.log(e.target.scrollLeft);
setOffsetX(e.target.scrollLeft);
}
返回(
...
...
)
};
导出默认主组件;
最终,我自己找到了解决方案。如果使用的是useRef
,而不是useState
,那么它将非常有效。当scroll事件触发时,div1
的scrollLeft
属性被设置为div2
的scrollLeft
属性的值,使用useRef
创建的引用
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;
const{useRef}=require('react');
常量MainComponent=()=>{
const div1=useRef(null);
const div2=useRef(null);
const onScroll=()=>{
div1.current.scrollLeft=div2.current.scrollLeft;
}
返回(
...
...
)
};
导出默认主组件;