Skip to main content
 首页 » 编程设计

react-native之react 原生 Android ScrollView scrollTo 不起作用

2024年12月31日12落叶无声

我正在尝试使用 React Native 中的水平 ScrollView 对于 Android,起始位置在滚动图像的中间而不是 (0,0)。
scrollTo方法似乎在 componentDidMount 内部被正确调用但应用程序中没有任何移动,它仍然显示为一直向左滚动。

根据文档,由于这是 Android,我无法访问 contentOffset Prop ,或者我会直接设置它。这是代码:

'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; 

请您参考如下方法:

我有同样的问题,浪费了几个小时没有它:

  • 1:在android中,ScrollView只有在其尺寸 <内容尺寸< li> 时才能滚动
  • 2:在react native 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"); 
        })   
    }