React Native Sync两个滚动视图

时间:2015-10-20 09:22:58

标签: react-native

React Native中是否有办法同步两个或多个滚动视图,以便它们相互跟随?我已经看到了Objective-c的一些实现,但是不知道如何为react native实现它。

2 个答案:

答案 0 :(得分:2)

  1. 根据this answer
  2. 滚动其中一个时,获取滚动位置
  3. 使用ScrollView.scrollTo
  4. 设置另一个的滚动位置

答案 1 :(得分:2)

到目前为止,我发现最干净,问题最少的是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(<View style={{ height: 50, backgroundColor: props.color1 }}><Text>{i}</Text></View>);
    squares.push(<View style={{ height: 50, backgroundColor: props.color2 }}><Text>{i}</Text></View>);
  }
  return squares;
}

export default class App extends Component {
  constructor(props) {
    super(props);
    this.leftIsScrolling = false;
    this.rigthIsScrolling = false;
  }
  render() {
    return (
      <View
        style={{flex: 1, alignItems: 'flex-start',backgroundColor: 'yellow'}}>
        <View style={{ backgroundColor: '#bbb', flexDirection: 'row' }}>

            <ScrollView
              scrollEventThrottle={16}
              ref={scrollView => { 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;
              }}>
              <Squares numRows={20} color1={"green"} color2={"darkgreen"} />
            </ScrollView>

          <ScrollView
            ref={scrollView => { 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;
            }}>
            <Squares numRows={20} color1={"red"} color2={"darkred"} />

          </ScrollView>
        </View>
      </View>
    );
  }
}

我也尝试过这个gist的行,但由于滚动位置的监听器总是影响两个ScrollView,所以行为很奇怪。

为此我受到answer的启发,关于如何在javascript中执行此操作。