RN 列表组件之一 ScrollView

RN 列表组件之一 ScrollView

滑动视图组件
// 常用的属性,不常用的到时候看源码
render(){
    <View style={{flex:1}}>
        <ScrollView 
            horizontal = 'true',  //默认为false 垂直滚动;true水平滚动
            showsHorizontalScrollIndicator = 'true', //水平滚动条
            showsVerticalScrollIndicator = 'false',  //垂直方向滚动条
            onContentSizeChange ={(contentWidth, contentHeight) = > {'滚动内容的视图发生变化时调用'}},
            refreshControl= 'true',
            refreshControl = {() => {}}
            pagingEnabled = 'true',   //开启分页功能

            ……          
        />
    </View>
}
// 制作一个轮播图
var Dimensions = require('Dimensions');
var {width} = Dimensions.get('window');
var TimerMixin = require('react-timer-mixin');
……
constructor(props){
    super(props);
    this.state = {
        // 注册定时器
        mixins: [TimerMixin],
        duration: 2000,
        currentPage: 0
    }
}
// 视图绘制完毕之后会调用此方法
componentDidMount() {
// 自动轮播
    this.startTimer();
},
render() {
    return (
        <View style={styles.container}>
          <ScrollView  style={styles.scrollViewStyle}
                ref="scrollView"
                horizontal={true}
                pagingEnabled={true}
                showsHorizontalScrollIndicator={false} 
                onMomentumScrollEnd={(e)=>this.onAnimationEnd(e)} //滑动一祯
                onScrollBeginDrag={this.onScrollBeginDrag}    //开始拖拽
                onScrollEndDrag={this.onScrollEndDrag}   //结束拖拽
          >
            {this.renderAllImages()}
          </ScrollView>
    <View style={styles.cycleStyle}>
    {this.renderAllCycle()}
  </View>
    </View>
  )
  },

  // 开启定时器
  startTimer() {
    // 拿到scrollView
    var scrollView = this.refs.scrollView;
    // 添加定时器
    this.timer = this.setInterval(function() {
          var tempPage;
          if (this.state.currentPage+1 >=7) {
             tempPage = 0;
          } else {
            tempPage = this.state.currentPage+1;
          }
          // 更新状态机
          this.setState( {
            currentPage: tempPage
          });
          // 改变scrollView的偏移量
          let offSet = tempPage * width;
          scrollView.scrollTo({x: offSet, y: 0, animated: true});
      }, this.state.duration);
    },
  // 当一帧滚动结束的时候会调用此方法
  onAnimationEnd(e) {
    // 获取偏移量
    let offset = e.nativeEvent.contentOffset.x;
    // 获取页码
    let page = Math.floor(offset / width);
    // 更新状态机,重新绘制UI
    this.setState({
      currentPage: page
    });
  },
  onScrollBeginDrag() {
    // 清除定时器
    this.clearInterval(this.timer);
  },
  onScrollEndDrag() {
    // 重新开启定时器
    this.startTimer();
  },
  // 返回所有图片
  renderAllImages() {
        var imageItems = [];
        var imageNames = ['1.jpg', '2.jpg', '3.jpg', '4.jpg','5.jpg', '6.jpg', '7.jpg'];
        var colors = ['red', 'blue', 'green', 'purple', 'brown', 'black', 'yellow'];
        for (var i=0; i<7; i++) {
          // 将Image装入数组中
          imageItems.push(
          <Image key={i}
          source={{uri: imageNames[i]}}
          style={{backgroundColor: colors[i], width: width, height: 300}} />
        );}
      // 返回所有Image
      return imageItems;
  },
  // 设置小圆点
  renderAllCycle() {
     var cycleItems = [];
     var colorStyle;
     for (var i=0; i<7; i++) {
       colorStyle = (i==this.state.currentPage) ? {color: 'gray'} : {color: 'white'}
      cycleItems.push(
      <Text key={i} style={[{fontSize: 30, left: 10}, colorStyle]}>&bull;</Text>)
    }
    return cycleItems;
  }
  })

// 设置样式
const styles = StyleSheet.create({
  container: {
    width: width,
    height: 300,
    backgroundColor: 'green',
  },
  scrollViewStyle: {
    backgroundColor: 'yellow',
    width:width,
    marginTop: 20
  },
  cycleStyle: {
    backgroundColor: 'rgba(241,241,241,0.5)',
    width: width,
    height: 30,
    position: 'absolute',
    bottom: 0,
    flexDirection: 'row',
    alignItems: 'center'
  }
});
### 解决React Native 中 `ScrollView` 组件不滚动的问题 在开发过程中遇到 `ScrollView` 不滚动的情况可能由多种因素引起。为了有效解决问题,需考虑几个常见原因并采取相应措施。 #### 1. 设置 ScrollView 的高度 如果 `ScrollView` 或其父容器的高度未被正确设置,则可能导致无法触发滚动行为。确保给定明确的高度属性可以解决此问题[^1]: ```javascript <ScrollView style={{ height: '100%' }}> {/* 子组件 */} </ScrollView> ``` #### 2. 使用 contentContainerStyle 属性 有时即使设置了外部样式也无法实现预期效果,这时可尝试通过 `contentContainerStyle` 来定义内部内容区域的样式,特别是当页面上存在多个子视图时更为重要: ```javascript <ScrollView contentContainerStyle={{ flexGrow: 1 }}> {/* 子组件 */} </ScrollView> ``` #### 3. 检查是否有其他交互阻止了滚动事件传播 某些情况下,可能会有其他的触摸处理逻辑干扰到了默认的滚动手势识别机制。确认没有额外的手势捕获器或其他会消耗掉触控事件的操作是非常必要的[^2]. #### 4. 调整嵌套 ScrollViews 行为 对于多层嵌套结构下的 `ScrollView`, 需要特别注意调整它们之间的相互作用方式。可以通过配置 `nestedScrollEnabled={true}` 参数来允许内层 `ScrollView` 正常工作而不影响外层的表现形式: ```javascript <ScrollView nestedScrollEnabled={true}> <ScrollView horizontal={true} nestedScrollEnabled={true}> {/* 子组件 */} </ScrollView> </ScrollView> ``` 以上方法能够帮助排查和修复大多数关于 `ScrollView` 不滚动的问题。当然,在实际项目中还可能存在更复杂的情形,建议根据具体场景灵活运用上述技巧进行调试优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值