問題
使用ScrollView的時(shí)候檬贰,react native有一個(gè)contentOffset變量,可以在渲染時(shí)設(shè)置初始變量缺亮,很多時(shí)候如果渲染成功在設(shè)置初始位置翁涤,會(huì)出現(xiàn)瞬間跳動(dòng)等問題。
然后iOS是沒有問題的,部分安卓機(jī)例如三星也是沒問題葵礼,但是類似華為這樣的安卓機(jī)就會(huì)出現(xiàn)失效的問題号阿,原因是出在Android某些系統(tǒng)沒有設(shè)置初始的scroll position導(dǎo)致的。
contentOffset設(shè)置方式如下:
<ScrollView style={{
flexDirection: 'row' ,
}}
ref={(ref) => { this.scrollViewRef = ref }}
pagingEnabled = {true}
bounces={false}
showsHorizontalScrollIndicator = {false}
showsVerticalScrollIndicator = {false}
horizontal = {true}
pagingEnabled={true}
alwaysBounceHorizontal = {true}
scrollEnabled = {false}
contentOffset = { this.state.filterNumber === 1 ? {x:ScreenUtil.screenW, y:0} : {x:0, y:0}}
>
解決方式
For anyone who can make this, these are the attributes in Android's native ScrollView.
android:scrollX The initial horizontal scroll offset, in pixels.
android:scrollY The initial vertical scroll offset, in pixels.
如果了解安卓的話鸳粉,在安卓端進(jìn)行重設(shè)初始變量扔涧。
不了解安卓的話,可以用另一種方式解決赁严,就是用React native方法:
有人肯定用這種方式解決:
componentDidMount() {
setTimeout(() => {
this.scrollView.scrollTo({x: 100});
}, 0);
}
但是這種是渲染后才滑動(dòng)的扰柠,理論上可以解決,但是很有可能還是會(huì)出現(xiàn)跳動(dòng)的情況疼约。
所以最佳解決方式如下:
<ScrollView
ref={scrollView => this.scrollView = scrollView}
onContentSizeChange={() => {
this._onContentSizeChange();
}}
></ScrollView>
_onContentSizeChange() {
let initialYScroll = 200;
this.scrollView.scrollTo({x: 0, y: 100, animated: false});
};
_onContentSizeChange API解釋如下:
Called when scrollable content view of the ScrollView changes.
Handler function is passed the content width and content height as parameters: (contentWidth, contentHeight)
It's implemented using onLayout handler attached to the content container which this ScrollView renders.
第一次渲染的時(shí)候一定會(huì)調(diào)用這個(gè)方法卤档,所以在這個(gè)方法內(nèi)去修改scrollView的初始位置即可,這樣就不會(huì)見到scrollView閃爍跳動(dòng)到指定位置的情況程剥。