【发布时间】:2020-11-03 05:21:01
【问题描述】:
我已经构建了一个反应组件,它在水平行中映射了许多产品卡。当这些卡片比屏幕长时,会发生溢出,并且组件底部会出现一个滚动条,允许用户沿着卡片左右滚动。我还希望在卡片上方显示一个滚动条,因此我添加了一个额外的 div,它从产品卡片 div 中获取其大小(通过 ref),并显示一个带有滚动条的空 div。然后,我将此 div 滚动位置与产品卡滚动位置相关联,反之亦然,以确保两者相同。这可行,但在滚动时显得不稳定/跳跃,尤其是在移动设备上。
我认为这可能是由于每个 onScroll 事件多次触发/相互矛盾,但无法弄清楚如何使其工作。任何帮助将不胜感激!
被渲染的组件:
<div>
{checkWidth() ? (
<div
className="ui link cards topscroll"
ref={topScrollRef}
onScroll={onScroll}
>
<div
style={{
minWidth: bottomScrollRef.current.scrollWidth,
overflowX: "scroll",
}}
></div>
</div>
) : (
""
)}
<div
ref={bottomScrollRef}
onScroll={onScroll}
className="ui link cards bottomscroll"
>
{renderList()}
</div>
</div>
还有 onScroll 事件处理程序:
const onScroll = (el) => {
if (
el.target.className === "ui link cards topscroll" &&
bottomScrollRef.current.scrollLeft !== topScrollRef.current.scrollLeft
) {
bottomScrollRef.current.scrollLeft = topScrollRef.current.scrollLeft;
} else if (
el.target.className === "ui link cards bottomscroll" &&
topScrollRef.current.scrollLeft !== bottomScrollRef.current.scrollLeft
) {
topScrollRef.current.scrollLeft = bottomScrollRef.current.scrollLeft;
}
};
注意:renderList() 返回产品卡片
【问题讨论】:
-
运气好能找到更好的方法吗?
-
很遗憾没有。我实际上最终删除了滚动条以避免该问题。不理想,但我找不到其他方法。对不起
-
我能理解。我还建议我的团队摆脱现有的滚动行为。并感谢您的回复。
-
@Helper 我在下面回答了我最终是如何重新实现的。仍然不是完美的,但比使用上面的参考要少得多。希望这会有所帮助!
-
非常感谢@webdog 就同样的问题回复我。
标签: javascript reactjs scroll ref