当我单击链接时,我正在尝试通过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
我想知道是否有更好的方法可以做到这一点?例如,始终重定向并滚动到顶部,因此即使我单击同一页面,它也仍会滚动
您可以像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')
);