2017-09-04 3 views
0

나는 반응을 사용하고 해시 변경 후 앵커 링크가 연결될 것으로 예상되는 곳을 조금 지나치려고합니다.id가 작동하지 않는 요소로 스크롤

나는 made a codesandbox here.

The answer provided here 작동합니다 있지만 어떤 이유로 그것을하지 않습니다. 내가 잘못 될 수있는 곳을 누군가가 볼 수 있습니까? 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> 
    ); 

} 
+0

무엇이 콘솔에 표시됩니까? – Script47

+0

일부 HTML 또는 피들러를 공유하여 문제를 시연하십시오! –

+0

jsfidde에서 코드를 시도했습니다. 작동합니다. https://jsfiddle.net/69z2wepo/85307/ – Andrew

답변

0

이것은 올바른 장소가 아닙니다. 구성 요소에 이벤트 핸들러가 있어야 작동합니다. 그렇지 않으면 모든 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> 
    ) 
    } 
} 
+0

이것은 여전히 ​​문제를 해결하지 않습니다 –

+0

방금 ​​코드 샘플을 업데이트했습니다. 다시 시도하십시오 :) – mersocarlin