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

posted @ 2020-03-16 00:26  YooHoeh  阅读(472)  评论(0编辑  收藏  举报
被你发现了?