我已经在react native中创建了一个表格,然后将其存储在firebase中。现在我想从firebase中检索该数据并以表格格式显示,我尝试了一些代码并制作了表格,但不知道如何容纳数据从表中的Firebase中获取。
这是我连接到Firebase以检索数据的代码。
import React,{Component} from 'react';
import {
Text,
TextInput,
View,
StyleSheet,
TouchableOpacity
} from 'react-native';
import {db} from '../config/db';
import {addDepts} from './dbServices';
import ItemComponent from './ItemComponent';
export default class ViewDept extends Component{
constructor(props){
super(props)
this.state={
departments:[]
}
}
componentDidMount() {
let currentComponent = this;
db.database().ref('custsf/').on('value', function(data) {
// console.log(snapshot.val());
//let data = snapshot.val();
// let departments = Object.values(data);
currentComponent.setState({departments:data.val()});
});
}
listenForItems=(addDepts) => {
addDepts.on("value", function(snapshot) {
console.log(snapshot.val());
let data = snapshot.val();
let departments = Object.values(data);
this.departments=departments;
});
}
render() {
return (
<View style={styles.container}>
{
this.state.departments.length > 0
? <ItemComponent items={this.state.departments} />
: <Text>No items</Text>
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 12,
},
})
这是我的带有虚拟数据的表格视图
import React, { Component } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, Alert } from 'react-native';
import { Table, TableWrapper, Row, Cell } from 'react-native-table-component';
import PropTypes from 'prop-types';
export default class ItemComponent extends Component {
constructor(props) {
super(props);
this.state = {
tableHead: ['Head', 'Head2', 'Head3', 'Head4'],
tableData: [
['1', '2', '3', '4'],
['a', 'b', 'c', 'd'],
['1', '2', '3', '4'],
['a', 'b', 'c', 'd']
]
}
}
static propTypes = {
items: PropTypes.array.isRequired
};
_alertIndex(index) {
Alert.alert(`This is row ${index + 1}`);
}
render() {
const state = this.state;
const element = (data, index) => (
<TouchableOpacity onPress={() => this._alertIndex(index)}>
<View style={styles.btn}>
<Text style={styles.btnText}>button</Text>
</View>
</TouchableOpacity>
);
return (
<View style={styles.container}>
<Table borderStyle={{borderColor: 'transparent'}}>
<Row data={state.tableHead} style={styles.head} textStyle={styles.text}/>
{
state.tableData.map((rowData, index) => (
<TableWrapper key={index} style={styles.row}>
{
rowData.map((cellData, cellIndex) => (
<Cell key={cellIndex} data={cellIndex === 3 ? element(cellData, index) : cellData} textStyle={styles.text}/>
))
}
</TableWrapper>
))
}
</Table>
</View>
)
}
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#808B97' },
text: { margin: 6 },
row: { flexDirection: 'row', backgroundColor: '#FFF1C1' },
btn: { width: 58, height: 18, backgroundColor: '#78B7BB', borderRadius: 2 },
btnText: { textAlign: 'center', color: '#fff' }
});