美文网首页
嵌套ScrollView解决方案

嵌套ScrollView解决方案

作者: 石小泉 | 来源:发表于2018-03-26 23:14 被阅读310次

场景

虽然设计上不赞成使用ScrollView进行嵌套,毕竟控制多个ScrollView的滑动事件是个坑,但是有时候还是架不住PM的需求😫

既然这样就只能想办法解决了

思路

ScrollView嵌套以后,必然会发生滑动事件冲突,我们只要每次只允许一个ScrollView可以滑动,应该就能避免冲突,嗯 就是这样

实现

ScrollView有一个scrollEnabled属性,可以用于控制ScrollView是否可以滑动,只要将其设置为false就能禁止其滑动操作

既然这样我们就用state来控制scrollEnabled

scrollEnabled={this.state.enabled}

滑动上面的一个ScrollView的时候,就禁止底层ScrollView的滑动

this.setState({enabled: false})

实例

code

import React, { Component } from 'react';
import { View, ScrollView } from 'react-native';

export default class App extends Component {
  constructor() {
    super();
    this.state = {
       enabled:true
    };
  }
  
  render() {
  return (
    <ScrollView scrollEnabled={this.state.enabled}>
      <View style={ {height:600,backgroundColor:'violet'}}></View>
      <View style={ { height: 2000, backgroundColor: 'red' }} >
      <ScrollView
        onTouchStart={(ev) => {this.setState({enabled:false }); }}
        onMomentumScrollEnd={(e) => { this.setState({ enabled:true }); }}
        onScrollEndDrag={(e) => { this.setState({ enabled:true }); }}
        style={ { margin: 10, maxHeight: 200 }}
    >
        <View style={ { height: 200, backgroundColor: 'blue' }} />
        <View style={ { height: 200, backgroundColor: 'pink' }} />
         <View style={ { height: 200, backgroundColor: 'blue' }} />
        <View style={ { height: 200, backgroundColor: 'pink' }} />
        <View style={ { height: 200, backgroundColor: 'blue' }} />
        <View style={ { height: 200, backgroundColor: 'pink' }} />
        <View style={ { height: 200, backgroundColor: 'blue' }} />
        <View style={ { height: 200, backgroundColor: 'pink' }} />
        <View style={ { height: 200, backgroundColor: 'blue' }} />
        <View style={ { height: 200, backgroundColor: 'pink' }} />
        <View style={ { height: 200, backgroundColor: 'blue' }} />
        <View style={ { height: 200, backgroundColor: 'pink' }} />
      </ScrollView>
      </View>
    </ScrollView>
  );
}
}

效果

nestedscrollview.gif

本文结束,欢迎大家加群共同学习

QQ群:672509442

😊😊😊😊

相关文章

网友评论

      本文标题:嵌套ScrollView解决方案

      本文链接:https://www.haomeiwen.com/subject/wmbdcftx.html