2017-10-30 5 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> 
); 
} 
} 
関連する問題