React Native Sync Two Scrollviews

前端 未结 2 1992
一个人的身影
一个人的身影 2021-02-09 09:40

Is there a way in React Native to sync two or more scrollviews so they follow each other? I\'ve seen some implementations for objective-c but have no idea how to implement that

2条回答
  •  被撕碎了的回忆
    2021-02-09 10:29

    So far the cleanest and less problematic I found was this:

    import React, { Component } from 'react'
    import { Text, View, ScrollView } from 'react-native'
    
    function Squares(props) {
        var squares = []
        for (var i = 0; i < props.numRows; i++) {
            squares.push({i})
            squares.push({i})
        }
        return squares
    }
    
    export default class App extends Component {
        constructor(props) {
            super(props)
            this.leftIsScrolling = false
            this.rigthIsScrolling = false
        }
        render() {
            return (
                
                    
    
                         { this._leftView = scrollView }}
                            onScroll={e => {
                                if (!this.leftIsScrolling) {
                                    this.rigthIsScrolling = true
                                    var scrollY = e.nativeEvent.contentOffset.y
                                    this._rightView.scrollTo({ y: scrollY })
                                }
                                this.leftIsScrolling = false
                            }}>
                            
                        
    
                         { this._rightView = scrollView }}
                            scrollEventThrottle={16}
                            onScroll={e => {
                                if (!this.rigthIsScrolling) {
                                    this.leftIsScrolling = true
                                    var scrollY = e.nativeEvent.contentOffset.y
                                    this._leftView.scrollTo({ y: scrollY })
                                }
                                this.rigthIsScrolling = false
                            }}>
                            
    
                        
                    
                
            )
        }
    }
    

    I have also tried something along the lines of this gist but it behaves strangely due to the listener in the scroll position is always affecting the two ScrollViews.

    For this I was inspired by this answer on how to do it in javascript.

提交回复
热议问题