首页 > 解决方案 > Flatlist 不会滚动;用额外空间渲染的单元格

问题描述

我遇到了这个非常奇怪的问题。当我用 呈现产品列表时FlatList,它在我的单元格之间放置了这个巨大的空间。(我已经注释掉了背景图像以加快加载速度,但无论哪种方式它的行为都相同)

ProductsListScreen.js

class ProductsListScreen extends Component<Props> {
  render() {
    return <WithFlatList products={this.props.products} />;
   // return <WithMap products={this.props.products} />;
  }
}

export default connect(({ productsReducer }) => ({
  products: Object.values(productsReducer.products)
}))(ProductsListScreen);

const WithFlatList = ({ products }) => {
  return (
    <FlatList
      data={products}
      renderItem={({ item }) => <ProductListCellView product={item} />}
      keyExtractor={item => `${item.id}`}
    />
  );
};

const WithMap = ({ products }) => {
  return (
    <ScrollView contentContainerStyle={styles.container}>
      {products.map(p => (
        <ProductListCellView product={p} key={p.id} />
      ))}
    </ScrollView>
  );
};

const styles = {
  container: {
    flex: 1,
    height: "100%"
  }
};

ProductsListCellView.js

const ProductListCellView = ({ product }: Props) => {
  return (
    <View style={styles.cellContainer}>
      <ImageBackground
        // source={{ uri: product.images[0].src }}
        style={styles.backgroundImage}
        imageStyle={styles.imageStyle}
      >
        <View style={styles.textContainer}>
          <NameText> {product.name} </NameText>
          <PriceText> ${product.price} </PriceText>
        </View>
      </ImageBackground>
    </View>
  );
};
export default ProductListCellView;

const styles = {
  cellContainer: {
    borderBottomWidth: 0.5,
    borderBottomColor: "grey",
    width: "100%",
    height: "50%",
    borderWidth: 3,
    backgroundColor: "lightblue"
  },
  backgroundImage: {
    width: "100%",
    height: "100%",
    justifyContent: "center"
  },
  imageStyle: {
    height: "140%",
    width: "140%",
    left: "-20%",
    top: "-20%"
  },
  textContainer: {
    backgroundColor: "black",
    maxWidth: "50%",
    padding: 5,
    opacity: 0.75
  }
};
const baseSize = 14;
const text = {
  name: {
    fontSize: baseSize + 8,
    fontWeight: "bold",
    color: "white"
  },
  price: { fontSize: baseSize + 4, color: "white" }
};
const NameText = props => <Text style={text.name}>{props.children}</Text>;
const PriceText = props => <Text style={text.price}>{props.children}</Text>;

在此处输入图像描述

似乎无论我设置什么heightcellContainer它都会将单元格呈现在屏幕的那个百分比(或某些基于屏幕高度的容器),然后在单元格的相同百分比处呈现单元格内容。

此外,列表没有滚动。我可以看到下一个单元格从底部向外窥视,因此整个列表正在呈现,但是当我尝试滚动时它只是反弹回来。我试过包装各种东西ScrollView,但没有运气。(我cellContainer在下面的屏幕截图中将高度更改为 15%)

当我手动映射项目时(将上面代码中的返回切换为使用`,高度工作正常,但滚动仍然不起作用:

在此处输入图像描述

其他人有这个问题吗?

标签: react-native

解决方案


height与其将of设置cellContainer为 % 值,不如将其设置为 static height,或者使用padding自动调整每个项目的大小。


推荐阅读