我目前正在建立卡片部分,其中显示了卡片的水平列表。该列表溢出,这使得用户必须水平滚动才能查看屏幕外的卡片。
为了使用户更轻松地进行此过程,我想创建将水平列表向左或向右滚动的按钮。
我尝试通过创建对水平列表的引用来解决此问题,并在单击上述按钮时应用了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>
);
答案 0 :(得分:8)
要使用Ref访问DOM节点,您需要使用ref.current
; useRef是DOM节点的容器,您可以使用current
属性访问该节点。
此外,scrollX
是只读属性;您需要调用scrollLeft
来更改滚动位置。为了使scrollLeft
起作用,您需要向overflow-x: scroll;
添加style.projects
规则才能起作用。 (如果style.projects
是对象,则更改为overflowX: 'scroll'
。)
要向左或向右滚动,可以在函数中为滚动偏移量添加一个参数,因此它并不总是向右滚动:
const scroll = (scrollOffset) => {
ref.current.scrollLeft += scrollOffset;
};
要执行此操作,您需要在JSX中使用两个按钮,以向左或向右传递滚动功能的偏移值:
<Row>
<Col>
<button onClick={() => scroll(-20)}>LEFT</button>
<button onClick={() => scroll(20)}>RIGHT</button>
</Col>
</Row>