2017-10-30 9 views
0

프로젝트에서 React Native로 작업하고 있으며 ScrollView 위치를 설정하고 싶습니다. 그래서 검색하고 나는 우리가 scrollTo이 작업을 수행해야 찾았지만 나는 오류가 있습니다scrollTo를 사용하고 싶습니다.

TypeError: Cannot read property 'scrollTo' of undefined 

내 코드 :

export default class Index_calendar extends Component { 
componentDidMount() { 
    const _scrollView = this.scrollView; 
    _scrollView.scrollTo({x: 100}); 
} 

render() { 
    return (
    <ScrollView ref={scrollView => this.scrollView = scrollView}> 
     {this.renderCalandar()} 
    </ScrollView> 
    ); 
} 
} 
+0

https://github.com/malte-wessel/react-custom-scrollbars/issues/196는 희망이 도움이됩니다 – Aaqib

+1

'scrollTo'는 [윈도우 API]의 일부입니다 (https : //로 개발. mozilla.org/en-US/docs/Web/API/Window/scrollTo) –

답변

0

당신은 올바른 참조를 만들 것입니다. 그러나 참조를 초기화하고 오류가 발생하지 않도록하는 것이 좋습니다.

export default class Index_calendar extends Component { 
constructor(props) { 
    super(props); 
    this.scrollView = null; 
} 

componentDidMount() { 
    const _scrollView = this.scrollView; 

    if (_scrollView) { 
    _scrollView.scrollTo({x: 100}); 
    } 
} 
0

해결책을 찾았습니다! 다음과 같이 setTimeout을 사용해야합니다.

setTimeout(() => { 
    this.scrollView.scrollTo({x: 100}); 
}, 1); 
0

렌더 메소드에서 scrollTo가 아닌 이유는 무엇입니까?

export default class Index_calendar extends Component { 
constructor(props) { 
    super(props); 
    this.scrollView = null; 
} 
render() { 
    return (
    <ScrollView ref={scrollView => { 
     //Sometimes ref can be null so we check it. 
     if(scrollView !== null && this.scrollView !== scrollView){ 
      this.scrollView = scrollView 
      scrollView.scrollTo({x: 100}); 
     }}> 
     {this.renderCalandar()} 
    </ScrollView> 
); 
} 
}