2017-12-13 1 views
7

사용자가 다른 구성 요소를 닫을 때 특정 구성 요소로 스크롤하려고합니다.React refs를 사용하여 scrollIntoView

우리의 예는 this.refs[elem].scrollIntoView()

를 호출하여 아래로 아래 https://reactjs.org/docs/refs-and-the-dom.html#exposing-dom-refs-to-parent-components

function CustomComponents(props) { 
    const items = [1,2,3,4].map((x, i) => return (
    <div ref={props.inputRef} key={i}> 
    x + hello 
    </div> 
) 

    return (
    <div> 
     { items } 
    </div> 
); 
} 

function Parent(props) { 
    return (
    <div> 
     <CustomComponents inputRef={props.inputRef} /> 
    </div> 
); 
} 


class Grandparent extends React.Component { 
    render() { 
    return (
     <Parent 
     inputRef={el => this.inputElement = el} 
     /> 
    ); 
    } 
} 

우리는 카드의 큰 목록을 렌더링하고 특정 카드로 스크롤 할 수 있도록하려는에서 가져온 것과 매우 유사하다 그러나 문제는 this.refs을 호출하면 모든 레벨에서 빈 객체가 반환되므로 특정 요소에 연결 한 다음 사용자가이 컴포넌트를보기 위해 다시 도착할 때 호출 할 수 없다는 것입니다.

이 문제를 해결하는 방법에 대한 도움이 필요하십니까?

+0

실제 예를 들어, 어떤 수준에서도 기능 구성 요소를 사용하지 않습니다. –

+1

콜백 함수를 사용하여 ref를 할당하면 this.inputElement –

+0

과 같은 클래스 변수 이름 대신 this.refs를 사용하여 더 이상 액세스하지 않습니다. @ShubhamKhatri 덕분에 우리의 두뇌가 죽어 버렸음이 밝혀졌습니다. 정말 우리를 도왔습니다. –

답변

1

어디에서 this.refs[elem].scrollIntoView()으로 전화를 걸려고하십니까? refcomponentDidMount 또는 componentDidUpdate 안에 넣고 render 방법이 아닌 곳에서 작업해야합니다.

+0

그래, 우리는 이미 행운없이 그것을하려고 노력하고 있었다, 그것을 해결할 수 있었다! :) –

0

나는 조부모 구성 요소에 아래에 작성된 if 문을 제공하여 특정 문제를 해결했습니다.

inputRef={el => { 
    if (el && el.id == this.state.selectedBuildingRef) { 
    this.myelement.scrollIntoView(); 
    window.scrollBy(0, -65); 
    } 
}} 
관련 문제