React Native 任务列表实战
import React, { useState } from 'react';
import { StyleSheet, Text, View, FlatList, TextInput, Button } from 'react-native';
const App = () => {
const [tasks, setTasks] = useState([{ id: 1, text: '学习React Native' }]);
const [inputText, setInputText] = useState('');
const addTask = () => {
const newTask = { id: Math.random(), text: inputText };
setTasks([...tasks, newTask]);
setInputText('');
};
const removeTask = (id) => {
setTasks(tasks.filter(task => task.id !== id));
};
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="输入任务"
value={inputText}
onChangeText={setInputText}
/>
<Button title="添加任务" onPress={addTask} />
<FlatList
data={tasks}
keyExtractor={item => item.id.toString()}
renderItem={({ item }) => (
<Text onPress={() => removeTask(item.id)} style={styles.item}>
{item.text}
</Text>
)}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
input: {
height: 40,
marginBottom: 10,
padding: 5,
},
item: {
padding: 10,
marginBottom: 5,
backgroundColor: '#f8f8f8',
},
});
export default App;
这段代码实现了一个简单的React Native任务列表应用,用户可以输入任务并添加到列表中,同时可以点击列表中的任务来删除它。代码使用了Hooks (useState
) 来管理状态,并展示了如何使用FlatList
组件来渲染列表项。
评论已关闭