2016-06-20 22 views
2

React Native ListViewの特定の行にスクロールする方法はありますか?ReactNative ListViewの行をスクロールしますか?

私はスクロールしたい行のインデックスを持っています。 this threadに続いて、スクロールしたい行への参照を取得できます。そして、私はlist's scrollTo functionを使ってスクロールすることができます。しかし、どうすればそれを結びつけることができますか?行のオフセットを見つけようとするすべてのメソッドは、私にNaNまたはその他のエラーを返します。

答えて

2

誰かが良い解決策を知っているかもしれませんが、私はスクロールのために次のユーティリティクラスを使用します。既に子を参照していると仮定すると、基本的な考え方はスクロールビュー内の子を測定してその位置を決定し、必要なオフセットを計算できるということです。

/** 
scroll child within scrollView. 

@param scrollView reference to scrollView 
@param child - measureable child (see measureLayout in https://facebook.github.io/react-native/docs/nativemethodsmixin.html) 
@param opt - options - (*default*) 
{ 
    destination : *'top'*, 'bottom' : where to scroll - to the top or bottom of view 
} 
*/ 
export function scrollTo(scrollView, child, opt = {}) { 
    const destination = opt.destination || TOP; 

    const handle = React.findNodeHandle(scrollView); 
    child.measureLayout(handle, (x,y, width, height) => { 
    // kind of hack - not really documented feature 
    scrollView.refs.ScrollView.measure((sx,sy, sw, sh, sPageX, sPageY) => { 
     scrollView.refs.InnerScrollView.measure((isx,isy, isw, ish, isPageX, isPageY) => { 
     console.log("scrollTo", x,y, width, height, sx,sy, sw, sh, sPageX, sPageY, isx,isy, isw, ish, isPageX, isPageY); 
     const currentScrollPosition = sPageY - isPageY; 
     if (currentScrollPosition <= y && y + height <= currentScrollPosition + sh) { 
      // the child fits into scroll view -> noop 
      console.log("fitting in"); 
     } else { 
      if (destination === TOP) { 
      if (y + sh > ish) { 
       // we would scroll too much (there is not so much content after child to fill whole scroll view) 
       scrollView.scrollTo({x:0, y: ish - sh}); 
      } else { 
       scrollView.scrollTo({x:0, y}); 
      } 
      } else { 
      scrollView.scrollTo({x:0, y: y + height - sh}); 
      } 
     } 
     }); 
    }); 
    }); 

} 

ノート - (彼らは再びscrollviewの内部を変更するまで:))それだけでRN0.27 +で動作します

+0

おかげで、私はそのような何かを試してみましたが、 'child.measureLayout'でエラーが発生します"レイアウトを測定しようとしましたが、オフセットまたはディメンションはNaNでした"。それが何であるか、どんな考えですか? – nicholas

+0

hm。決して私には起こりません。おそらくhttp://stackoverflow.com/questions/31617206/react-native-get-the-position-of-a-component-in-the-view - ただし、私はユーザーの操作に応じてスクロールするだけなので、起こるべきではありませんあまりに早く測定していることを私に伝えてください。 – sodik

関連する問題