我正在尝试从我的react应用程序上的导航栏滚动到特定的div。我使用了react-scroll,但在滚动到div时仍然有问题。我的导航条码是这样的。
<Nav className="mr-auto">
<ScrollLink
to="contact"
spy={true}
smooth={true}
duration={500}
className='Home'
activeClass='Home'>
Contact
</ScrollLink></Nav>而div代码是
<Element id='contact' name='contact'>
** My div here
</Element>我也尝试过使用scroller.scrollTo方法在Onclick事件中使用锚标记,但没有产生任何结果。
scroller.scrollTo('contact', {
duration: 1500,
delay: 100,
smooth: true,
offset: 50
});我是不是漏掉了什么?
发布于 2020-03-15 03:18:25
使用react-scroll v1.7.16,尝试执行以下操作:
import { Link, Element, Events, scrollSpy } from "react-scroll"
class App extends React.Component {
// Optional: if you want to do some stuff when the event begin/end
componentDidMount() {
Events.scrollEvent.register("begin", function(to, element) {
console.log("begin", arguments)
})
Events.scrollEvent.register("end", function(to, element) {
console.log("end", arguments)
})
scrollSpy.update()
}
// Remove the event listener to avoid memory leaks and side effects
componentWillUnmount() {
Events.scrollEvent.remove("begin")
Events.scrollEvent.remove("end")
}
render() {
return (
<div className="App">
<Link
to="myElement"
spy={true}
smooth={true}
duration={500}
>
Scroll to element
</Link>
<Element name="myElement" className="element">
Element
</Element>
</div>
)
}
}
export default App下面是一个有效的codeSandbox示例。
然而,您不需要库来做到这一点,您可以简单地给您的目标div一个唯一的ID选择器:
<div id="mydiv" />然后以a标签为目标,如下所示:
<a href="#mydiv" />最后,将此代码添加到您的css:
html {
scroll-behavior: smooth;
}
const App = () => {
return (
<div className="App">
<a href="#elementID">Scroll to your div</a>
<div style={{height: 500}} />
<div id="elementID">my div!</div>
<div style={{marginTop: 500}} />
</div>
)
}
ReactDOM.render( <App /> , document.getElementById('root'))html {
scroll-behavior: smooth;
}<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
https://stackoverflow.com/questions/60685176
复制相似问题