一、ScrollView滚动视图
其中有个方法是ScrollTo 滚动到指定的x, y偏移处。第三个参数为是否启用平滑滚动动画。
scrollTo(y: number | { x?: number, y?: number, animated?: boolean }, x: number, animated: boolean)
使用示例:
scrollTo({x: 0, y: 0, animated: true})
具体使用方法举例:
第一种:
使用measure测量出位置
<Container>
<Content>
<ScrollView
horizontal={true}
ref={(view) => { this.myScrollView = view; }}
>
<View></View>
<View ref={view => this.totop = view}>
想跳转的位置
</View>
</ScrollView>
</Content>
<Footer>
<Button onPress={this.clickToScroll}>点击滑动到指定位置</Button>
</Footer>
</Container>
clickToScroll = () => {
//先用measure测量出位置
this.refs.totop.measure((fx, fy, width, height, px, py) => {
console.log('Component width is: ' + width)
console.log('Component height is: ' + height)
console.log('X offset to frame: ' + fx)
console.log('Y offset to frame: ' + fy)
console.log('X offset to page: ' + px)
console.log('Y offset to page: ' + py)
//然后用scrollTo跳转到对应位置
//x是水平方向
//y是垂直方向
this.myScrollView.scrollTo({ x: px, y: py, animated: true });
});
}
第二种:
使用onLayout方法计算出位置
onLayout 当组件挂载或者布局变化的时候调用,参数为:
{nativeEvent: { layout: {x, y, width, height}}}
这个事件会在布局计算完成后立即调用一次,不过收到此事件时新的布局可能还没有在屏幕上呈现,尤其是一个布局动画正在进行中的时候。
<Container>
<Content>
<ScrollView
ref={(view) => { this.myScrollView = view; }}
>
<View></View>
<View onLayout={event=>{this.layout = event.nativeEvent.layout}}>
想跳转的位置
</View>
</ScrollView>
</Content>
<Footer>
<Button onPress={this.clickToScroll}>点击滑动到指定位置</Button>
</Footer>
</Container>
clickToScroll = () => {
// 其中this.layouot.y就是距离现在的高度位置
this.myScrollView.scrollTo({ x: 0, y: this.layout.y, animated: true});
}
ScrollView中的 horizontal={true} 水平排列,水平滚动,默认没有,是垂直方向。
注意:当ScrollView在组件Content中滑动ios有时候会有一些问题,解决办法不放在Content或者用以下方法滑动
第二种:
添加插件react-native-keyboard-aware-scroll-view
在代码头部引入import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
以上的代码中用KeyboardAwareScrollView替换Content
clickToScroll = () => {
//测量的宽度和高度还是用以上的方法
//直接用scrollToPosition跳转到相应的位置
this.myContent.scrollToPosition(0,this.layoutY.y)
}
以上。。。