React native - ScrollView 通過(guò)contentOffset不能找到初始位置的問(wèn)題

問(wèn)題

使用ScrollView的時(shí)候,react native有一個(gè)contentOffset變量,可以在渲染時(shí)設(shè)置初始變量,很多時(shí)候如果渲染成功在設(shè)置初始位置,會(huì)出現(xiàn)瞬間跳動(dòng)等問(wèn)題。

然后iOS是沒(méi)有問(wèn)題的,部分安卓機(jī)例如三星也是沒(méi)問(wèn)題,但是類似華為這樣的安卓機(jī)就會(huì)出現(xiàn)失效的問(wèn)題,原因是出在Android某些系統(tǒng)沒(méi)有設(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ì)見(jiàn)到scrollView閃爍跳動(dòng)到指定位置的情況。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容