在React Native中动态添加和删除表行可以通过以下步骤实现:
以下是一个示例代码:
import React, { Component } from 'react';
import { View, Text, Button, FlatList } from 'react-native';
class DynamicTable extends Component {
constructor(props) {
super(props);
this.state = {
tableData: [
{ id: 1, name: 'Row 1' },
{ id: 2, name: 'Row 2' },
{ id: 3, name: 'Row 3' }
]
};
}
handleAddRow = () => {
const { tableData } = this.state;
const newRow = { id: tableData.length + 1, name: `Row ${tableData.length + 1}` };
const newTableData = [...tableData, newRow];
this.setState({ tableData: newTableData });
}
handleDeleteRow = (index) => {
const { tableData } = this.state;
const newTableData = [...tableData];
newTableData.splice(index, 1);
this.setState({ tableData: newTableData });
}
renderRow = ({ item, index }) => {
return (
<View key={item.id} style={{ flexDirection: 'row' }}>
<Text>{item.name}</Text>
<Button title="Delete" onPress={() => this.handleDeleteRow(index)} />
</View>
);
}
render() {
const { tableData } = this.state;
return (
<View>
<Button title="Add Row" onPress={this.handleAddRow} />
<FlatList
data={tableData}
renderItem={this.renderRow}
keyExtractor={(item) => item.id.toString()}
/>
</View>
);
}
}
export default DynamicTable;
在上述示例中,我们使用FlatList组件来展示表格数据,并为每个表行添加了一个删除按钮。点击添加按钮会在表格末尾添加一行数据,点击删除按钮会删除对应的表行数据。
领取专属 10元无门槛券
手把手带您无忧上云