在構建函數聲明一個記錄位置的值
constructor(){
this.positionY = ''
}
既然要滾動,那肯定得將組件放在ScrollView
裏面啦
<ScrollView ref={ref => this.scrollRef = ref}>
<View onLayout={e=>{this.positionY = e.nativeEvent.layout.y}}> //這個onLayout方法會在組件渲染的時候執行,
<Comp/> //這裏可以是任意你想定位的組件,可以是原生組件也可以是自定義組件
<View>
</ScrollView>
接下來就是滾動函數了
this.refs.scrollRef &&
this.refs.scrollRef.scrollTo({
x: 0,
y: this.positionY,
animated: true
});
如果覺得使用
View
組件來獲取指定組件高度會影響你的佈局,可以使用Fragment
組件或者<></>
同樣也具有onLayout
方法。