嗨,我正在尝试在滚动的开始和结束位置禁用/隐藏水平滚动条的箭头按钮。 我试图通过设置其依赖项document.getElementById('hscroll')。scrollLeft来使用useEffect生命周期,以便我可以在scrollLeft更改时触发一个函数...但是在加载时它显示错误“无法读取属性'scrollLeft' null”,这显然是正确的。
代码在这里... hscroll CodeSandBox
我该怎么做? 需要您的帮助!
预先感谢您<3。
答案 0 :(得分:0)
您只能使用useState
钩子和条件渲染来做到这一点。
这是一个完全正常的解决方案,假设我们知道包裹幻灯片的div宽度:
const HorizontalScroll = () => {
const [slideLeft, setSlideLeft] = useState(0);
const sliderWidth = 1900;
//on arrow click
const moveRight = () => {
const el = document.getElementById(`hscroll`);
setSlideLeft(el.scrollLeft += 200);
};
const moveLeft = () => {
const el = document.getElementById(`hscroll`);
setSlideLeft(el.scrollLeft -= 200);
};
return (
<div className="homepageMargin">
<section style={{ display: "flex", justifyContent: "space-between" }}>
{slideLeft > 0 ? <IconButton onClick={moveLeft}>
<ArrowBackIcon
style={{
paddingTop: ".2rem",
cursor: "pointer"
}}
/>
</IconButton> : <div />}
{slideLeft < sliderWidth ? <IconButton onClick={moveRight}>
<ArrowForwardIcon
style={{
paddingTop: ".2rem",
cursor: "pointer"
}}
/>
</IconButton> : <div />}
</section>
<hr style={{ backgroundColor: "black" }} />
<div class="flex-container" id={`hscroll`}>
{data.map((item) => (
<div style={{ minWidth: "300px" }}>
<img src={item.imgSrc} alt="images" style={{ width: "18rem" }} />
<h6>{item.title}</h6>
</div>
))}
</div>
</div>
);
};
上面的示例可以正常工作,因为每次更新状态时,React组件都会重新渲染。另外,您可以像这样获得滑块的宽度:
const sliderWidth = yourRefName.current.style.width;
但是必须在CSS中明确声明。