[英]React Native - How to get the measures of renderItem in Flatlist
I have a horizontal Flatlist
where items can be of different heights.我有一个水平
Flatlist
,其中项目可以具有不同的高度。 How can I get the height of all elements or a specific visible element and, depending on the element's height, change the height of the Flatlist
?如何获取所有元素或特定可见元素的高度,并根据元素的高度更改
Flatlist
的高度?
I made a code close to mine on Snack .我在Snack上做了一个接近我的代码。 In the example, the height in
data
is indicated for the example, in my code I DON'T KNOW this height .在示例中,
data
中的高度为示例指示,在我的代码中我不知道这个高度。
I would be very grateful for your help!我将非常感谢您的帮助!
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>
);
}
I'm not sure what is your main goal here but assuming that you what all items to be the same height (given by the item with the biggest height), you can use onLayout
to get the highest value.我不确定您的主要目标是什么,但假设您所有项目的高度相同(由具有最大高度的项目给出),您可以使用
onLayout
来获得最高值。 Something like this:像这样的东西:
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>
)
}
you can try to use itemHeight
on the FlatList as well and see how that plays out.您也可以尝试在 FlatList 上使用
itemHeight
,看看效果如何。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.