У меня есть список данных о сотрудниках. Мне нужны линии сетки между ними (для просмотра в виде таблицы). Как это возможно с flatList в React Native?
<View >
<View style = {Styles.empTab}>
<ScrollView horizontal = {true} >
<View style = {Styles.empTable}>
<Text>SL#</Text>
<FlatList
//style = {Styles.empData}
data = {this.state.empData}
keyExtractor = {item => item.emp_id + ""}
renderItem = {({ item }) => (
<View style = {Styles.empitem}>
<Text>{item["emp_id"]}</Text>
</View>
)}
/>
</View>
<View style = {Styles.empTable}>
<Text>Name</Text>
<FlatList
//style = {Styles.empData}
data = {this.state.empData}
keyExtractor = {item => item.emp_id + ""}
renderItem = {({ item }) => (
<View style = {Styles.empitem}>
<Text>{item["name"]}</Text>
</View>
)}
/>
</View>
</ScrollView>
</View>
Результат такой как
SL# Name
1 ab
2 gh
Мне нужно просмотреть его как таблицу (т.е. с границей столбца-строки)
@Siraj Я пробовал с этим, но он не отображается в виде таблицы
Можете поделиться скриншотом, как он выглядит? Также поделитесь своей таблицей стилей.





Вы можете использовать свойство ItemSeparatorComponent из FlstList
Итак, создайте одну функцию, которая будет возвращать вид разделителя:
renderSeparatorView = () => {
return (
<View style = {{
height: 1,
width: "100%",
backgroundColor: "#CEDCCE",
}}
/>
);
};
Теперь воспользуйтесь этим методом в FlatList.
<FlatList
...
ItemSeparatorComponent = {this.renderSeparatorView}
/>
Это создаст вид горизонтального разделителя.
Для стиля изменения вида вертикального разделителя, например:
style = {{
height: 100%,
width: "1",
backgroundColor: "#CEDCCE",
}}
Нашел простой способ создать вашу таблицу, для этого я использую реагировать-родной-таблица-компонент.
import React, { Component } from "react";
import { StyleSheet, View } from 'react-native';
import { Table, TableWrapper, Row, Rows } from 'react-native-table-component';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
tableHead: ['SL#', 'Name'],
tableData: [
['1', 'ab'],
['2', 'gh'],
['3', 'asdf'],
]
}
}
render() {
const state = this.state;
return (
<View style = {styles.container}>
<Table>
<Row data = {state.tableHead} flexArr = {[1, 1]} style = {styles.head} textStyle = {styles.text} />
<TableWrapper style = {styles.wrapper}>
<Rows data = {state.tableData} flexArr = {[1, 1]} style = {styles.row} textStyle = {styles.text} />
</TableWrapper>
</Table>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
paddingTop: 30,
backgroundColor: '#fff'
},
head: {
height: 40,
backgroundColor: '#f1f8ff'
},
wrapper: {
flexDirection: 'row'
},
title: {
flex: 1, backgroundColor: '#f6f8fa'
},
row: {
height: 28
},
text: {
textAlign: 'center'
}
});
Подробнее читайте здесь: https://www.npmjs.com/package/react-native-table-component
Здесь ItemSeparatorComponent будет отображать горизонтальную границу, а элемент визуализации - вертикальную границу. Пример ниже будет работать для двух столбцов, вы можете изменить индекс% 2 к тому, что у вас есть numColumns. Например, если numColumns равно 3, то это будет индекс% 3
<FlatList
numColumns = {2}
ItemSeparatorComponent = {this.renderSeparator}
</FlatList>
renderSeparator = () => (
<View
style = {{
backgroundColor: 'black',
height: 1
}}
/>
);
renderItem = {({ item, index }) => (
<Text style = {[styles.text, index % 2 !== 0 && {borderLeftWidth: 1, borderLeftColor: 'black'}]}>{item}</Text>
)}
что вы имеете в виду под индекс% 2! == 0 в <Text style = {[styles.text, index% 2! == 0 && {borderLeftWidth: 1, borderLeftColor: 'black'}]}> {item} </Text>
Это оператор условного стиля, который означает, что borderLeft будет присутствовать только в том случае, если индекс элемента не делится на 2.
Я решил эту проблему, используя приведенный ниже код renderRow. У меня есть 2 столбца в виде сетки. Измените длину столбца, заменив X в индекс% X === 0 и индекс <= Y, где Y - столбцы-1
renderRow({ item, index }) {
return (
<View style = {[styles.GridViewContainer,
index % 2 === 0 ? {
borderLeftWidth: 1, borderLeftColor: 'black',
borderRightWidth: 1, borderRightColor: 'black',}
:
{borderRightWidth: 1, borderRightColor: 'black'}
,{borderBottomWidth: 1, borderBottomColor: 'black'}
,index <= 1 && {borderTopWidth: 1, borderBottomColor: 'black'}
]}
>
... render item code ...
</View>
)
}
просто укажите границу компонента в вашем методе обратного вызова renderItem