单击按钮时水平滚动组件

问题描述 投票:2回答:1

我目前正在建立一个卡片部分,其中显示了卡片的水平列表。此列表溢出,这使得用户必须水平滚动才能查看屏幕外的卡片。

为了使用户更容易执行此过程,我想创建将水平列表向左或向右滚动的按钮。

我尝试通过创建对水平列表的引用来解决此问题,并在单击前面提到的按钮时应用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>
);
javascript reactjs react-hooks
1个回答
1
投票

为了使用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>
© www.soinside.com 2019 - 2024. All rights reserved.