我目前正在构建一个卡片区域,其中显示了一个水平卡片列表。该列表会溢出,因此用户必须水平滚动以查看屏幕外的卡片。
为了让用户更轻松地进行此操作,我想创建按钮,可以将水平列表向左或向右滚动。
我尝试通过创建对水平列表的引用并在单击上述按钮时应用scrollX来解决此问题。然而,这会导致以下错误:
Cannot add property scrollX, object is not extensible
我的代码:
const ref = useRef(null);
const scroll = () => {
ref.scrollX += 20;
};
return (
<div className={style.wrapper} id={id}>
<Container className={style.container}>
<Row>
<Col>
<button onClick={scroll}>TEST</button>
</Col>
</Row>
</Container>
<div className={style.projects} ref={ref}>
{projects.map((data, index) => (
<CardProject
key={index}
title={data.title}
image={data.image}
description={data.description}
/>
))}
</div>
</div>
);
style.projects
的 CSS 中添加scroll-behavior: smooth;
,但这在 Safari 中不被原生支持,所以您需要使用一些 polyfill,比如 https://github.com/iamdustan/smoothscroll。 - litel