簡體   English   中英

嘗試使用 react-scroll 滾動到特定的 div

[英]Trying to scroll to a particular div using react-scroll

我正在嘗試從我的 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
});

我在這里錯過了什么嗎?

使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM