React Native滾動到指定位置

在構建函數聲明一個記錄位置的值

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方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章