先说明一下使用背景吧==>用ScrollView写的一个页面,页面底部有一个下一篇按钮,但是点击按钮重新render之后,页面依旧在底部,没有自动跳到顶部,视觉效果很差
解决的方法是在ScrollView的标签中加入相当于类名的属性
<ScrollView ref = 'totop' > <View style ={styles.container} > <View style ={styles.top} >< Text style ={{ color : '#1eaaca' }} >{this.state.ClassTitle} </ Text ></View > <View >< Text style ={{ fontSize : 20, lineHeight : 60, }} >{this.state.title} </ Text ></View > <TouchableHighlight onPress ={() => { this. getPrevious() }} > <View > <View style ={styles.iconboder} > <View style ={styles.border} ></View > </View > < Text >上一篇 </ Text > </View > </TouchableHighlight > </ScrollView>
其中的ref='totop',==>ref相当于锚点的id属性,'totop'是随意的命名,相当于类名
在调用这个方法的组件中这样书写
<TouchableHighlight onPress ={() => { this. getPrevious()//点击调用的方法 }} > <View > <View style ={styles.iconboder} > <View style ={styles.border} ></View > </View > < Text >上一篇 </ Text > </View > </TouchableHighlight >在点击调用的方法getPrevious()中
getPrevious(){
//这里是控制页面的初始位置的方法,相当于html中利用id的锚点连接方法, totop相当于类名,组件的ref相当于锚点id,refs指同一类方法. this.refs.totop. scrollTo({x : 0,y : 0,animated : true}); 需要三个参数,x轴的起始点,y轴的起始点.anmated是指是否有动画效果
}
项目中的整体方法比较复杂,这里简单把功能写出来了,大家参考下.
简单理解就是ref的一些属性控制的,大家可以看一下ref的详解.
