简体   繁体   English

通过id滚动到某个元素不起作用

[英]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. 我正在使用React并尝试滚动一点点,以更改哈希更改后锚链接应该链接到的位置。

I have made a codesandbox here. 在这里做了一个codesandbox。

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. 虽然确实会调用scrollToId函数,但是由于某些原因无法滚动到我想要的位置。

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. 否则,您将在每个render方法上多次初始化相同的addEventListener事件。

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>
    )
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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