与 recyclerlistview 一起使用时自定义禁用 ScrollView 滚动

问题描述 投票:0回答:1

我有以下 React Native 代码。

import { ScrollView } from 'react-native';

import {
  DataProvider,
  LayoutProvider,
  RecyclerListView,
} from "recyclerlistview";

const MyComponent = () => {
  // define DataProvider & LayoutProvider here

  return (
    <ScrollView>
      // some content

      <RecyclerListView
        // props
      />
    </ScrollView>
  )
}

如您所见,

recyclerlistview
嵌套在
ScrollView
内部,起始位置如下。

enter image description here

当我继续滚动时,在

ScrollView
保留在顶部的大约 50 像素处,它会被禁用。
recyclerlistview
本身仍然可以滚动。

enter image description here

此行为似乎特定于

recyclerlistview
,因为将其替换为
FlatList
或另一个
ScrollView
不会禁用父级
ScrollView
的滚动。

似乎总是禁用顶部留有 50 像素

ScrollView
的滚动,无论我在
recyclerlistview
之前添加什么填充/边距/内容。

我的问题是,是否可以将高度指定为 50px 以外的值?

谢谢

react-native scrollview recyclerlistview
1个回答
0
投票

您可以通过

onScroll
onMomentumScrollEnd
动态调整滚动/高度。在下面的示例中,手柄滚动用于设置
contentOffset.y
启用/禁用滚动偏移值小于或大于 50 的值。

参考以下代码:

import React, { useRef } from 'react';
import { ScrollView, View, Text, Dimensions, StyleSheet } from 'react-native';
import {
  DataProvider,
  LayoutProvider,
  RecyclerListView,
} from "recyclerlistview";

const { height } = Dimensions.get('window');

const MyComponent = () => {
  const scrollViewRef = useRef(null);
  const [scrollEnabled, setScrollEnabled] = React.useState(true);

  const dataProvider = new DataProvider((r1, r2) => r1 !== r2).cloneWithRows([
    // some other code comes here...
  ]);

  const layoutProvider = new LayoutProvider(
    index => 0,
    (type, dim) => {
      dim.width = Dimensions.get('window').width;
      dim.height = 100; // Set height as needed
    }
  );

  const handleScroll = (event) => {
    const offsetY = event.nativeEvent.contentOffset.y;
    if (offsetY >= 50) {
      setScrollEnabled(false);
    } else {
      setScrollEnabled(true);
    }
  };

  const handleMomentumScrollEnd = (event) => {
    const offsetY = event.nativeEvent.contentOffset.y;
    if (offsetY < 50) {
      setScrollEnabled(true);
    }
  };

  return (
    <ScrollView
      ref={scrollViewRef}
      onScroll={handleScroll}
      scrollEnabled={scrollEnabled}
      onMomentumScrollEnd={handleMomentumScrollEnd}
      scrollEventThrottle={16}
    >
      {/* your-data-here */}
      <View style={styles.content}>
        <Text>Some content before RecyclerListView</Text>
      </View>
      <RecyclerListView
        layoutProvider={layoutProvider}
        dataProvider={dataProvider}
        rowRenderer={(type, data) => (
          <View style={styles.item}>
            <Text>{data}</Text>
          </View>
        )}
      />
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  content: {
    height: height / 3, // Change this value as per your need
    justifyContent: 'center',
    alignItems: 'center',
  },
  item: {
    height: 100,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default MyComponent;

© www.soinside.com 2019 - 2024. All rights reserved.