单击按钮时水平反应滚动组件

Jon*_*ers 7 javascript reactjs react-hooks

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

为了让用户更轻松地完成此过程,我想创建向左或向右滚动水平列表的按钮。

我尝试通过创建对水平列表的引用并在单击前面提到的按钮时应用 scrollX 来解决此问题。但是,这会导致以下错误:

Cannot add property scrollX, object is not extensible
Run Code Online (Sandbox Code Playgroud)

我的代码:

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>
);
Run Code Online (Sandbox Code Playgroud)

lit*_*tel 19

为了使用 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;
};
Run Code Online (Sandbox Code Playgroud)

为此,您需要在 JSX 中使用两个按钮,将向左或向右的偏移值传递给滚动函数:

 <Row>
        <Col>
          <button onClick={() => scroll(-20)}>LEFT</button>
          <button onClick={() => scroll(20)}>RIGHT</button>
        </Col>
  </Row>
Run Code Online (Sandbox Code Playgroud)

  • @JonathanLauwers您可以将“scroll-behavior:smooth;”添加到“style.projects”的CSS中,但这在Safari中不受本机支持,因此您需要某种polyfill,例如https://github.com/伊姆达斯坦/smoothscroll (3认同)