首页 > 解决方案 > 如何在本机反应中使 FlatList 在 ScrollView 内可滚动?

问题描述

我想在 ScrollView 组件中创建一个 FlatList,但我不断收到错误消息“VirtualizedLists 永远不应嵌套在具有相同方向的普通 ScrollViews 中,因为它可能会破坏窗口和其他功能 - 请改用另一个 VirtualizedList 支持的容器。” 这导致了我这篇文章。我能够将我的代码更改为以下几点,但我不确定如何更改this.refs.myList.scrollProperties.offset以适合我的代码。这是尝试将 FlatList 放入 ScrollView 的最佳方法还是有更好的方法?

const [enableScrollViewScroll, setEnableScrollViewScroll] = useState(true);

return (
  <View 
    onStartShouldSetResponderCapture={() => {
      setEnableScrollViewScroll(true);
    }}>
    <ScrollView 
      scrollEnabled={enableScrollViewScroll}>
      <Component/>
      <View
        onStartShouldSetResponderCapture={() => {
          setEnableScrollViewScroll(false);
          if (this.refs.myList.scrollProperties.offset === 0 && enableScrollViewScroll === false) {
            setEnableScrollViewScroll(true);
          }
        }}>
        <FlatList 
          data={myData}
          renderItem={({item}) => (
            <Text style = {{
              borderWidth: 1,
              marginTop: 5,
              borderRadius: 3,
              paddingLeft: 3,
            }}> 
              {item.content}
            </Text>
          )}/>
      </View>
    </ScrollView>
  </View>
);

标签: react-nativereact-native-flatlistreact-native-scrollview

解决方案


我遇到了一个非常相似的问题,直到我在对 react-native 项目的一个 GitHub 问题的非常有用的评论中遇到了一个几乎完整的解决方案:https ://github.com/facebook/react-native/issues/1966 #issuecomment-285130701

问题是父组件是唯一注册滚动事件的组件。解决方案是根据印刷机的位置根据上下文决定哪个组件实际上应该处理该事件。

您需要稍微修改您的结构以:

<View>
<ScrollView>
    <View>
        <FlatList/>
    </View>
    <View>
        <FlatList/>
    </View>
    <View>
        <FlatList/>
    </View>
    <View>
        <FlatList/>
    </View>
</ScrollView>
</View>

或者:

我们可以为子 FlatList/ScrollView 组件使用内置的nestedscrollenabled属性。

<FlatList nestedScrollEnabled />

This is only required for AndroidiOS 默认支持嵌套滚动)。


推荐阅读