在运行时计算FlatList行组件的高度 [英] Calculating height for FlatList row components during run time
本文介绍了在运行时计算FlatList行组件的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想设计一个有4行的FlatList,每行应该占据FlatList的1/4高,每行之间的间距为5px。作为一名原生iOS开发人员,我对如何在Reaction-Native的FlatList中实现这一点感到有点困惑。我不知道在呈现ROW组件的哪个阶段可以应用该计算。不应该使用下面的代码片段来实现我已经解释过的逻辑:
getItemLayout={(data, index) => (
{length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}
)}
提前谢谢。
推荐答案
APP.JS
import React, { Component } from 'react';
import {
StyleSheet,
SafeAreaView
} from 'react-native';
import SplitFlatList from './components/SplitFlatList'
class App extends Component {
render() {
return(
<SafeAreaView style={styles.container}>
<SplitFlatList></SplitFlatList>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
header: {
height: 200
}
})
export default App;
SPLITFLATLIST.JS
import React, { Component } from 'react'
import {
StyleSheet,
View,
FlatList,
Text
} from 'react-native'
export default class SplitFlatList extends Component {
constructor() {
super()
this.state = {
componentHeight: 0
}
}
renderSeparator = () => {
return (
<View
style={{
height: 5,
width: "100%",
backgroundColor: 'white',
}}
/>
);
};
renderItem = (index, item) => {
var { color } = 'white'
switch(index) {
case 0: color = 'skyblue'; break
case 1: color = 'red'; break
case 2: color = 'lightgreen'; break
case 3: color = 'navy'; break
default: color = 'white'; break
}
return(
<View style={[styles.row, {height: (this.state.componentHeight - 15) / 4}, {backgroundColor: color}]}>
<Text>item</Text>
</View>
)
}
render() {
return(
<View style={styles.container} onLayout = {event => this.setDimension(event)}>
<FlatList
data = {['1', '2', '3', '4']}
renderItem = {({item, index}) =>
this.renderItem(index, item)
}
ItemSeparatorComponent = {this.renderSeparator}
scrollEnabled = {false}
/>
</View>
)
}
setDimension(event) {
console.log(event.nativeEvent.layout.height)
this.setState({
componentHeight: event.nativeEvent.layout.height
})
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
row: {
backgroundColor: 'pink'
}
})
这篇关于在运行时计算FlatList行组件的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文