简体   繁体   English

FlatList 不滚动

[英]FlatList not scrolling

i have created a screen where I display a component that contains a FlatList.我创建了一个屏幕,在其中显示一个包含 FlatList 的组件。 For some reason I can't scroll through the list.出于某种原因,我无法滚动列表。 Someone who can spot my mistake and point me in the right direction?谁能发现我的错误并指出正确的方向?

render-function and style from my screen file:我的屏幕文件中的渲染功能和样式:

render() {
return (
  <View style={styles.container}>
    <SearchBar />
    <ActivityList style={styles.list} data={this.state.data} />
  </View>
);
}
}

const styles = StyleSheet.create({
 container: {
  flex: 1,
  overflow: 'hidden',
  backgroundColor: '#fff',
  alignItems: 'center',
  justifyContent: 'flex-start',
 },
 list: {
  flex: 1,
  overflow: 'hidden',
 },
});

render function and style from my listitem component:从我的 listitem 组件渲染 function 和样式:

export default class CardItem extends React.PureComponent {
render() {
return (
  <View style={styles.cardview}>
    <View style={styles.imagecontainer}>
      <Image
        resizeMode="cover"
        style={styles.cardimage}
        source={{
          uri: this.props.image,
        }}
      />
    </View>
    <View style={styles.cardinfo}>
      <Text style={styles.cardtitle}>{this.props.title}</Text>
      <View style={styles.cardtext}>
        <Text style={styles.textdate}>{this.props.date}</Text>
        <Text style={styles.texthour}>{this.props.hour}</Text>
      </View>
    </View>
  </View>
);
}
}

const styles = StyleSheet.create({
 cardview: {
  flex: 1,
  justifyContent: 'flex-start',
  backgroundColor: 'white',
  elevation: 3,
  maxHeight: 200,
  width: Dimensions.get('window').width - 20,
  margin: 1,
  marginTop: 10,
  borderRadius: 4,
},
imagecontainer: {
 flex: 7,
 height: 140,
 borderRadius: 4,
},
cardimage: {
 flex: 1,
 opacity: 0.8,
 height: 140,
 borderTopLeftRadius: 4,
 borderTopRightRadius: 4,
},
cardinfo: {
 flex: 2,
 flexDirection: 'row',
 justifyContent: 'space-between',
 alignItems: 'center',
 padding: 10,
},
cardtitle: {
 flex: 1,
 fontSize: 16,
 fontWeight: 'bold',
},
cardtext: {
 flex: 1,
 justifyContent: 'center',
 alignItems: 'flex-end',
},
textdate: {
 color: '#5e5e71',
},
texthour: {
 color: '#5e5e71',
},
});

render function and style from my list component:从我的列表组件中渲染 function 和样式:

export default class ActivityList extends React.Component {
_renderCardItem = ({ item }) => (
<CardItem
  image={item.image}
  title={item.title}
  date={item.date}
  hour={item.hour}
/>
);

_keyExtractor = item => item.id;

render() {
return (
  <FlatList
    data={this.props.data}
    renderItem={this._renderCardItem}
    contentContainerStyle={styles.cardcontainer}
    keyExtractor={this._keyExtractor}
  />
);
}
}

const styles = StyleSheet.create({
 cardcontainer: {
  flex: 1,
  overflow: 'hidden',
  backgroundColor: 'white',
  alignItems: 'center',
  width: Dimensions.get('window').width,
  borderWidth: 0,
 },
});

my data items have all a unique id, title, date, hour.我的数据项都有唯一的 ID、标题、日期、时间。

Read through all available guides and docs and found no solution.通读所有可用的指南和文档,但没有找到解决方案。

Take out the flex: 1 in your styles.cardcontainer , that should let you scroll.在你的styles.cardcontainer取出flex: 1 ,它应该让你滚动。 The FlatList/ScrollView contentContainerStyle prop wraps all the child components—what's "inside" the FlatList if you will—and should never have a defined height or flex value. FlatList/ScrollView contentContainerStyle道具包装了所有的子组件——如果你愿意的话,“在”FlatList 里面是什么——并且永远不应该有一个定义的高度或 flex 值。 If you need to set a flex: 1 for the FlatList itself use style={{flex: 1}} instead.如果您需要为 FlatList 本身设置flex: 1 ,请改用style={{flex: 1}} Cheers!干杯!

I also meet this issue when I'm adding image tool in my chatting app, and found a trick solution.我在聊天应用程序中添加图像工具时也遇到了这个问题,并找到了一个技巧解决方案。

By simply add TouchableWithoutFeedback to cover every element in flatlist.通过简单地添加 TouchableWithoutFeedback 来覆盖 flatlist 中的每个元素。 Strange but it works.奇怪,但它的工作原理。

_renderCardItem = ({ item }) => (
<TouchableWithoutFeedback onPress={()=>{}}>
<CardItem
  image={item.image}
  title={item.title}
  date={item.date}
  hour={item.hour}
/>
</TouchableWithoutFeedback>
);

Simply do following steps to get FlatList scroll.只需执行以下步骤即可获得 FlatList 滚动。

<View style={{flex:1}}>
  <FlatList
    data={this.state.data}
    renderItem={({item}) => this.renderData(item)}
    keyExtractor={item => item._id}
    contentContainerStyle={{
    flexGrow: 1,
    }}
  />
</View>

For others coming to this question: My FlatList was inside a TouchableWithoutFeedback.对于遇到这个问题的其他人:我的 FlatList 在 TouchableWithoutFeedback 内。 I changed that to a View and was able to scroll again.我将其更改为视图并能够再次滚动。

for me the problem was the size of an image inside the flatlist item.对我来说,问题是 flatlist 项目内图像的大小。 I just set it's height by percentage which was a mistake.我只是按百分比设置它的高度,这是一个错误。

here are some tips.这里有一些提示。

1: don't put a fixed height for FlatList contentContainer 1:不要给FlatList contentContainer 设置一个固定的高度

2: childs inside Flatlist must not have a height of percentage eg: 50% otherwise it take the half of list and don't let other childs to render 2:Flatlist 内的孩子不能有百分比的高度,例如:50% 否则它会占据列表的一半,不要让其他孩子渲染

3: if you want to have a fixed size FlatList put it's height inside style property not contentContainerStyle 3:如果你想要一个固定大小的 FlatList 把它的高度放在 style 属性中而不是 contentContainerStyle

I have faced the same problem for FlatList.我在 FlatList 中遇到了同样的问题。

<View style={styles.list}>
<FlatList/>
</View>

I used flex : 1, flexGrow :1 for list style .我使用flex : 1, flexGrow :1作为列表样式。 then it working for me .那么它对我有用。

My FlatList was able to scroll although I had it inside a TouchableWithoutFeedback.我的 FlatList 能够滚动,尽管我将它放在 TouchableWithoutFeedback 中。 My problem was I had an onPressIn event on my FlatList items which interfered with the scroll detection.我的问题是我的 FlatList 项目上有一个 onPressIn 事件,它干扰了滚动检测。 It worked after I changed it to onPress.在我将其更改为 onPress 后它起作用了。

Add the following columnWrapperStyle :添加以下列columnWrapperStyle

` <FlatList
    horizontal={false}
    data={products}
    columnWrapperStyle={{ flexWrap: 'wrap' }}
    numColumns={2}
    renderItem={renderItem}
    keyExtractor={(item, index) => index} />`

As many of you, guys, I've also faced the issue with a FlatList not to be scrolling if it has some specific positioning applied to it ( position: 'absolute' or moving outside the bounds of it's parent View by setting negative margin values, etc.).和你们中的许多人一样,如果 FlatList 应用了一些特定的定位( position: 'absolute'或通过设置负边距值移动到它的父视图的边界之外,我也遇到过这样的问题:FlatList 不能滚动, ETC。)。 As it often happens, neither one of proposed solutions did the trick for me, so I decided to investigate this case in a sandbox.正如经常发生的那样,没有一个解决方案对我有用,所以我决定在沙箱中调查这个案例。

There is my test app:有我的测试应用程序:

import React, { useState } from "react";
import { View, Text, FlatList, TouchableOpacity } from "react-native";

const App = () => {
  const [toggle, setToggle] = useState(false);
  const [selection, setSelection] = useState("");

  const data = [];
  for (let i = 0; i < 10; i++) {
    data.push({ key: `${i}`, text: `Item ${i}` });
  }

  function renderList() {
    return (
      <View style={{ width: "100%", zIndex: 5 }}>
        <TouchableOpacity
          style={{ width: "100%", height: 40, backgroundColor: "#CCCCCC", padding: 10 }}
          onPress={() => setToggle(!toggle)}
        >
          <Text>{selection}</Text>
        </TouchableOpacity>
        {toggle && (
          <FlatList
            style={{
              width: "100%",
              height: 150,
              backgroundColor: "#FFFFFF",
              top: 40,
              position: "absolute",
              zIndex: 10,
            }}
            data={data}
            renderItem={({ item }) => (
              <TouchableOpacity
                style={{ width: "100%", padding: 5 }}
                onPress={() => {
                  setSelection(item.text);
                  setToggle(!toggle);
                }}
              >
                <Text>{item.text}</Text>
              </TouchableOpacity>
            )}
          />
        )}
      </View>
    );
  }

  return (
    <View style={{ flex: 1, backgroundColor: "#777777", padding: 10 }}>
      {renderList()}
      <View style={{ width: "100%", height: 40, backgroundColor: "#AAAAAA", marginTop: 10 }} />
    </View>
  );
};

export default App;

The idea is as simple as possible - 2 "controls" on the "screen", the topmost one represents a dropbox that has to cover the second "control" below with a dropdown list.这个想法尽可能简单——“屏幕”上有 2 个“控件”,最上面的一个代表一个下拉框,必须用下拉列表覆盖下面的第二个“控件”。 Such layout will definitely need some manipulation with z-ordering as the topmost "control" initially has lower z-index than the second one, making the dropdown to appear under the second "control".这样的布局肯定需要对 z 排序进行一些操作,因为最顶层的“控件”最初的 z-index 低于第二个,使得下拉菜单出现在第二个“控件”下。
And my conclusion is the following: you should not change zIndex of a parent (or grandparent...) of your FlatList (see zIndex: 5 style in my code and try to remove it) if it doesn't fully enclose FlatList bounds .我的结论如下:如果它没有完全包含 FlatList bounds ,则不应更改zIndex的父级(或祖父级...)的 zIndex (请参阅我的代码中的zIndex: 5样式并尝试将其删除)。 Instead you can do it for the Flatlist itself (as I did, and zIndex: 10 works fine).相反,您可以为 Flatlist 本身执行此操作(就像我所做的那样,并且zIndex: 10可以正常工作)。

NB : Another styling option that should block scrolling and appears to be completely inobvious is setting backgroundColor of a parent View.注意:另一个应该阻止滚动并且看起来完全不明显的样式选项是设置父视图的backgroundColor颜色。 But you probably will not use it as it will also break effect of setting zIndex for the FlatList.但是你可能不会使用它,因为它也会破坏为 FlatList 设置zIndex的效果。

For me, I had an absolutely positioned transparent view on top of my list!对我来说,我的列表顶部有一个绝对定位的透明视图!

For whatever reason, it only affected my android version.无论出于何种原因,它只影响了我的 android 版本。

I think the absolute position made it so the inspector didn't see it when I looked.我认为绝对位置使它这样检查员在我看时没有看到它。

In my case, I had a TouchableWithoutFeedback wrapper at the top, which was used to remove keyboard popup when clicking anywhere.就我而言,我在顶部有一个TouchableWithoutFeedback包装器,用于在单击任意位置时删除键盘弹出窗口。 This was causing the FlatList to not scroll.这导致FlatList无法滚动。 Once, removed the FlatList was behaving normally.一次,删除FlatList行为正常。

我有类似的问题,但它实际上是我使用两根手指滚动的方式,就像在 Mac 上正常滚动一样,而不是用手指双击,按住然后滚动

for me, the solution was to wrap the whole FlatList with a View whose height set to 100%对我来说,解决方案是用高度设置为 100%的 View 包裹整个 FlatList

const styles = StyleSheet.create({
  container: {
    padding: "8px",
    height: "100%"
  },
});

<View style={styles.container}>
  <FlatList
    { /* ... */ }
  />
</View>

in my case, it was the "position: 'absolute' on the flatlist styling that made it not scrolling在我的情况下,是平面列表样式上的“位置:'绝对'”使它不滚动

Could be where you import from, for me对我来说可能是你从哪里进口的

import {ScrollView } from "react-native-gesture-handler";从“react-native-gesture-handler”导入{ScrollView};

won't scroll but不会滚动但是

import {ScrollView} from "react-native";从“react-native”导入 {ScrollView};

will.将要。 I had a vscode extension auto add the import and it chose the gesture-handler for some reason我有一个 vscode 扩展自动添加导入,它出于某种原因选择了手势处理程序

Got similar issue that FlatList does not scroll, none of the solutions mentioned above did not help.遇到 FlatList 不滚动的类似问题,上面提到的解决方案都没有帮助。 Even copy-pasting the code did not help.即使复制粘贴代码也无济于事。 Fixed by trying the app on real device, instead of Android emulator and what a surprise - it works.通过在真实设备上尝试该应用程序而不是 Android 模拟器来修复,这真是一个惊喜 - 它有效。 On other emulators it also works, so issue can be emulator, not a code.在其他模拟器上它也可以工作,所以问题可以是模拟器,而不是代码。

If all else failed like me, restart the debug session (eg react-native run-android)如果一切都像我一样失败,请重新启动调试 session(例如 react-native run-android)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM