【问题标题】:React Native - How to get the measures of renderItem in FlatlistReact Native - 如何在 Flatlist 中获取 renderItem 的度量
【发布时间】:2022-01-25 04:00:31
【问题描述】:

我有一个水平的Flatlist,其中的项目可以有不同的高度。如何获取所有元素或特定可见元素的高度,并根据元素的高度更改Flatlist 的高度?

我在Snack 上创建了一个与我的代码接近的代码。在示例中,data 中的高度用于示例,在我的代码中我不知道这个高度

非常感谢您的帮助!

import React from 'react';
import { View, StyleSheet, FlatList, Text, Dimensions } from 'react-native';
const {width} = Dimensions.get('window');

const Item = ({item}) => {
  return (
    <View style={{width, height: item.height, backgroundColor: 'yellow'}}>
      <Text>{item.type}</Text>
      <Text>{item.text}</Text>
    </View>
  );
};

export default function App() {
  const data = [
    { 
      height: 100, //FOR EXAMPLE
      type: 'row 1', 
      text: 'row 1'
    },
    { 
      height: 200, //FOR EXAMPLE
      type: 'row 2', 
      text: 'row 2'
    },
    { 
      height: 150, //FOR EXAMPLE
      type: 'row 3', 
      text: 'row 3'
    },
  ];

  return (
    <View>
      <FlatList
        style={{backgroundColor: 'red'}}
        data={data}
        keyExtractor={item => item.id}
        renderItem={({item}) => (
            <Item item={item} />
          )
        }
        horizontal
        pagingEnabled
      />
    </View>
  );
}

【问题讨论】:

    标签: react-native react-native-flatlist flatlist


    【解决方案1】:

    我不确定您在这里的主要目标是什么,但假设您的所有项目都具有相同的高度(由具有最大高度的项目给出),您可以使用 onLayout 来获得最高值。像这样的:

    const Item = ({ item, height, setHeight }) => {
      return (
        <View
          style={{ width, height: height, backgroundColor: 'yellow' }}
          onLayout={({ layout }) => (onLayout.height > height ? setHeight(layout.height) : false)} // If current item height is bigger then the rest, update height for all of them
        >
          <Text>{item.type}</Text>
          <Text>{item.text}</Text>
        </View>
      )
    }
    
    export default function App() {
      const [itemHeight, setItemHeight] = useState(0) // Keep track of height
      // ... data
    
      return (
        <View>
          <FlatList
            style={{ backgroundColor: 'red' }}
            data={data}
            keyExtractor={(item) => item.id}
            renderItem={({ item }) => (
              <Item item={item} height={itemHeight} setHeight={setItemHeight} />
            )}
            horizontal
            pagingEnabled
          />
        </View>
      )
    }
    
    

    您也可以尝试在 FlatList 上使用 itemHeight,看看效果如何。

    【讨论】:

    • 我需要Flatlist 的高度取决于当前可见项目的高度并动态更改。如果您查看Snack 示例,您将看到Flatlist 标记为red,而该项目标记为yellow。这里我需要Flatlist 的高度等于项目的高度,因此没有多余的红色
    猜你喜欢
    • 2018-06-04
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    相关资源
    最近更新 更多