Morton
Morton

Reputation: 5782

How to get each item's height into getItemLayout if the height is dynamic?

I want to use getItemLayout to let <FlatList /> more efficient.

But when use onLayout to get my list height that is not stable, maybe 128 or 230 or 183.

So set itemHeight for 128 into getItemLayout is not working properly.

Is any other way to let my itemHeight get the dynamic height into my getItemLayout?

onLayout(event) {
  const {x, y, height, width} = event.nativeEvent.layout;
  console.log('height:', height); // the height is dynamic
}

renderItem = ({ item }) => {
  return (
    <View onLayout={(event) => this.onLayout(event)} style={styles.floorView} style={styles.itemView}>
      <Text>{item.name}</Text>
    </View>
  );
}

<FlatList
  data={DUMMY_LIST}
  ref={(ref) => { this.flatListRef = ref; }}
  renderItem={this.renderItem}
  numColumns={1}
  keyExtractor={(item, index) => index.toString()}
  getItemLayout={(data, index)=> {
  return { length: itemHeight, offset: itemHeight * index , index };
  }}
/>

Upvotes: 9

Views: 2312

Answers (0)

Related Questions