简体   繁体   中英

scrolling to an element by id not working

I am using React and trying to scroll a little past where an anchor link is supposed to link to after a hash change.

I have made a codesandbox here.

The answer provided here should work but for some reason it isn't. Can anyone see where I may be going wrong? The scrollToId function does get called, but for some reason doesn't scroll to my desired location.

const Page = () => {

    let scrollToId = () => {

        if(location.hash.length !== 0) {

            window.scrollTo(window.scrollX, window.scrollY + 200);

        }

    }

    window.addEventListener("hashchange", scrollToId);

   return (
      <div>
          <a href="#one">Link</a>
          <p id="one">One</p>
      </div>
      );

}

This is not the correct place to handle that. You need an event handler on your component in order to make it work. Otherwise you initialize the same addEventListener event multiple times on every render method.

import React, { Component } from 'react'

export default class YourComponent extends Component {
  constructor(props) {
    super(props)

    this.handleScroll = this.handleScroll.bind(this)
  }

  componentDidMount() {
    window.addEventListener('hashchange', this.handleScroll) // Initialize your listener
  }

  componentWillUnmount() {
    window.removeEventListener('hashchange', this.handleScroll) // Remove your listener
  }

  handleScroll() {
    if (window.location.hash.length !== 0) {
      window.scrollTo(window.scrollX, window.scrollY + 200)
    }
  }

  render() {
    return (
      <div>
        <a href="#one">Link</a>
        <p id="one">One</p>

        <div style={{ height: 900 }} />

        <div style={{ backgroundColor: 'red', width: 600, height: 100 }}>
          Content
        </div>
      </div>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM