React Native - VirtualizedLists 永远不应该嵌套在具有相同方向的普通 ScrollViews 中

React Native - VirtualizedLists should never be nested inside plain ScrollViews with the same orientation

我正在为带有 expo cli 的现有 Web 应用程序开发一个应用程序。

我已完成主屏幕,但在使用 ScrollView

时收到此警告

VirtualizedLists should never be nested inside plain ScrollViews with the same orientation - use another VirtualizedList-backed container instead.

我有一个文件夹 screens,其中包含网站的所有页面。所以目前我 Home.js 有不同的部分。

<View>
  <Showcase />
  <StepsList />
  <HomeInfo />
  <HomeCorporateMenu />
  <HomeMonthlyMenus />
</View>

然后在根组件中渲染这个组件App.js。但我无法向下滚动以查看其他部分。

所以我添加了 SafeAreaViewScrollView 组件。现在我可以滚动了,但有时我会在控制台中收到警告。

我已经查过了,找到了一些解决方案。

已将 style={{ flex: 1 }}keyboardShouldPersistTaps='always' 添加到 ScrollView 组件

但仍然收到相同的警告。有什么建议吗?

<SafeAreaView style={styles.container}>
  <ScrollView>
    <Header />
    <HomeScreen />
  </ScrollView>
</SafeAreaView>

警告显然是在告诉您,您不应嵌套多个具有相同方向的 VirtualizedList(FlatList 和 SectionList)组件(列表的方向可能是 vertical)。

要正确执行并使警告消失,您必须使用 VirtualizedListListHeaderComponent or ListFooterComponent 属性并像这样嵌套它们:

const App = () => {
  const ListFooterComponent = (
    <>
      <FlatList
        // other FlatList props
        data={stepsListData}
      />
      <FlatList
        // other FlatList props
        data={homeInfoData}
      />
      <FlatList
        // other FlatList props
        data={homeCorporateMenuData}
      />
      {/* ... */}
    </>
  );

  return (
    <FlatList
      // other FlatList props
      data={showcaseData}
      ListFooterComponent={ListFooterComponent}
    />
  );
};

或者另一种可能的解决方法(而不是官方解决方案)是使用带有空 datarenderItem 属性的 FlatList而不是使用 ScrollView。而不是这个:

const App = () => {
  return (
    <SafeAreaView style={styles.container}>
      <ScrollView>
        <Header />
        <HomeScreen />
      </ScrollView>
    </SafeAreaView>
  );
};

你可以使用这个:

const emptyData = [];

const renderNullItem = () => null;

const App = () => {
  const ListFooterComponent = (
    <>
      <Header />
      <HomeScreen />
    </>
  );

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={emptyData}
        renderItem={renderNullItem}
        ListFooterComponent={ListFooterComponent}
      />
    </SafeAreaView>
  );
};