30

Androidの React Native で水平 ScrollViewを使用しようとしています。開始位置は (0,0) ではなくスクロール画像の中央にあります。

メソッドはscrollTo内部で正しく呼び出されているように見えますcomponentDidMountが、アプリケーション内で何も移動せず、スクロールを左端まで開始しているように表示されます。

ドキュメントによると、これは Android であるため、 contentOffset プロパティにアクセスできないか、直接設定します。コードは次のとおりです。

'use strict';

var React = require('react-native');
var {
  StyleSheet,
  View,
  Text,
  ScrollView,
  Component,
} = React;
var precomputeStyle = require('precomputeStyle');

class Carousel extends Component {
  constructor(props, context) {
    super(props, context);
    //this.changeContent = this.changeContent.bind(this);
  }

  componentDidMount() {
    this.myScroll.scrollTo(100);
    console.log("called DidMount");
  }

  render() {
    return (
      <View style={{flex: 1}}>
        <ScrollView ref={(ref) => this.myScroll = ref}
          contentContainerStyle={styles.container}
          horizontal={true}
          pagingEnabled={true}
          showsHorizontalScrollIndicator={false}
          bounces={true}
          onMomentumScrollEnd={this.onAnimationEnd}
        >
          {this.props.children}
        </ScrollView>
      </View>
    );
  }

  onAnimationEnd(e) {
    console.log("curr offset: " + e.nativeEvent.contentOffset.x);
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  page: {
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
  },
});

module.exports = Carousel;
4

5 に答える 5

47

私は同じ問題を抱えていて、数時間を無駄にしました:

  • 1: Android では、ScrollView はそのサイズ < コンテンツのサイズの場合にのみスクロールできます

  • 2: 反応ネイティブ Android では、componentDidMount で ScrollView.scrollTo() を呼び出しても機能しません。ScrollView には作成時にレイアウト アニメーションがあるため、ReactScrollView.java で見つけることができます。

protected void onLayout(boolean changed, int l, int t, int r, int b) {
    // Call with the present values in order to re-layout if necessary
    scrollTo(getScrollX(), getScrollY());
}

そのため、アニメーションの後に遅らせる必要があります

componentDidMount() {
    InteractionManager.runAfterInteractions(() => {
      this.myScroll.scrollTo(100);
        console.log("called DidMount");
    })  
}
于 2016-01-06T03:46:29.937 に答える
26

遅延とタイマーの使用を避けたかったので、少し掘り下げた後、使用onLayoutが非常にスムーズに機能することがわかりました。

scrollToInitialPosition = () => {
  this.scrollViewRef.scrollTo({ y: 100 });
}
...
<ScrollView
  ref={(ref) => { this.scrollViewRef = ref; }}
  onLayout={this.scrollToInitialPosition}
/>
于 2019-01-22T14:28:26.563 に答える
22

これは React Native 0.44.0 で動作します。ヒント@Eldelshellをありがとう。また、任意のタイムアウト値でも機能するようです。少なくともエミュレータでは。問題を解決するために何も答えInteractionManager.runAfterInteractionsなかったことがわかりましたが、おそらくそれはバージョンの違いです。

componentDidMount() {
  setTimeout(() => {
    this._scroll.scrollTo({y: 100})
  }, 1)
}
于 2017-05-28T18:47:40.427 に答える