【问题标题】:React Router and scrollTo behaviour反应路由器和滚动行为
【发布时间】:2020-05-14 20:09:22
【问题描述】:

当我点击一个链接时,我正在尝试使用 React Router 获得以下功能。

假设这是我当前的位置:page/1

如果我当前在第 1 页 (page/1) 上并单击指向 page/1 的链接,我希望浏览器滚动到页面顶部使用诸如 window.scrollTo 之类的平滑行为。

如果我在任何其他页面上,例如page/2,我想要标准重定向行为

完成这样的事情的最佳方法是什么?我想到了类似的东西:

if current location === page I'm trying to access -> scroll behaviour

else Redirect

我想知道是否有更好的方法来做到这一点?例如,总是重定向并滚动到顶部,所以即使我点击同一页面,它仍然会滚动

【问题讨论】:

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

你可以像https://www.npmjs.com/package/react-scroll这样的图书馆

// ES6 Imports
import { animateScroll as scroll } from 'react-scroll'

var Section = React.createClass({

  scrollToTop: function() {
    scroll.scrollToTop();
  },

  handleSetActive: function(to) {
    console.log(to);
  },
  render: function () {
    return (
      <div>
        <Link activeClass="active" to="test1" spy={true} smooth={true} offset={50} duration={500} onSetActive={this.handleSetActive}>
          Test 1
        </Link>
        <Link activeClass="active" to="test1" spy={true} smooth={true} offset={50} duration={500} delay={1000}>
          Test 2 (delay)
        </Link>
        <Link className="test6" to="anchor" spy={true} smooth={true} duration={500}>
          Test 6 (anchor)
        </Link>
        <Button activeClass="active" className="btn" type="submit" value="Test 2" to="test2" spy={true} smooth={true} offset={50} duration={500} >
          Test 2
        </Button>

        <Element name="test1" className="element">
          test 1
        </Element>

        <Element name="test2" className="element">
          test 2
        </Element>

        <div id="anchor" className="element">
          test 6 (anchor)
        </div>


        <Link to="firstInsideContainer" containerId="containerElement">
          Go to first element inside container
        </Link>

        <Link to="secondInsideContainer" containerId="containerElement">
          Go to second element inside container
        </Link>
        <div className="element" id="containerElement">
          <Element name="firstInsideContainer">
            first element inside container
          </Element>

          <Element name="secondInsideContainer">
            second element inside container
          </Element>
        </div>

        <a onClick={this.scrollToTop}>To the top!</a>
      </div>
    );
  }
});

React.render(
  <Section />,
  document.getElementById('example')
);

【讨论】:

  • 我认为对于像这样的简单用例导入一个 100kb 的库有点不必要。肯定有更简单的方法可以做到这一点?
猜你喜欢
  • 1970-01-01
  • 2021-02-05
  • 2017-12-20
  • 2016-08-18
  • 2017-06-14
  • 2021-11-02
  • 2021-08-08
  • 2020-09-30
  • 2017-10-12
相关资源
最近更新 更多