【问题标题】:Jump to sequential tags by one button一键跳转到顺序标签
【发布时间】:2020-06-02 15:59:02
【问题描述】:

我有以下源代码(React.js、React-scroll、React-bootstrap)。 点击 div,跳转到特定的图片标签。(在本例中,跳转到第一张图片。)

render(){
  return(
    <React.Fragment>
      <Modal>
        <Modal.Header>
          <div className="jump-to-image">
            <Link to="page-image-1" containerId="containerElement"></Link>
          </div>
        </Modal.Header>
        <Modal.Body>
          <Element name="scroll-area" className="document-content-page-images" id="containerElement">
            {this.renderPageImages()}
          </Element>
        <Modal.Body>
        ...
  )
}
renderPageImages(){
  return _.map(page_images, (page_image, i) => (
    <Element key={i} name={"page-image-" + (i + 1)}>
      <img className="document-content-page-image" src={`/thumbnail?path=...}`}/>
    </Element>
  ))
}

但我希望(单个)按钮按顺序跳转到图像标签。

第一次点击:跳转到第一个图片标签(page-image-1)
第二次点击:跳转到下一个图片标签(page-image-2)
第三次点击:跳转到下一个图片标签(page-image-3)
...
Image that what I want.

请告诉我如何实现。

【问题讨论】:

  • 提供其他细节——状态变量、按钮代码等

标签: javascript html reactjs react-scroll


【解决方案1】:

给你

不需要&lt;Link&gt;,您可以使用简单的button,在单击时滚动后立即增加计数,因此下次单击时您可以滚动到下一个元素

scroller.scrollTo("page-image-" + scrollTo, {

工作演示

代码:

import React, { useState } from "react";
import "./styles.css";
import { Element, scroller } from 'react-scroll'

// fake data to loop through
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

export default function App() {
  // use state to maintain the last/next to scroll index
  const [scrollTo, setScrollTo] = useState(1);

  const scrollToElement = () => {

    // You can scroll to element by it's name
    scroller.scrollTo("page-image-" + scrollTo, {
      duration: 1500,
      delay: 100,
      smooth: true,
      offset: 0 // Scrolls to element + 50 pixels down the page
    });

    // increment the state, so on next click you can scroll to next element
    setScrollTo(scrollTo => scrollTo + 1);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={scrollToElement}>Scroll to {scrollTo}</button>
      {data.map(d => (
        <Element name={`page-image-${d}`} className="block"> // <--- Element
          Scroll to : {d}
        </Element>
      ))}
    </div>
  );
}

【讨论】:

  • 非常感谢。这正是我想要的。我从你的回答中学到了很多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-09
  • 2013-12-06
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多