반응형
App.js
import { StatusBar } from 'expo-status-bar';
import React, {useState} from 'react';
import { StyleSheet, Text, View, FlatList, } from 'react-native';
import Header from './components/header';
import TodoItem from './components/todoItem';
import AddTodo from './components/addTodo';
export default function App() {
const[todos, setTodos] = useState([
{text: 'buy coffee', key: '1'},
{text: 'create an app', key: '2'},
{text: 'play on the switch', key: '3'},
]);
const pressHandler = (key) => {
setTodos((prevTodos) =>{
return prevTodos.filter(todo => todo.key != key)
})
}
const submitHandler = (text) => {
setTodos((prevTodos) => {
return [
{ text: text, key: Math.random().toString() },
...prevTodos,
]
})
}
return (
<View style={styles.container}>
{ /*header*/}
<Header></Header>
<View style={styles.content}>
{/* to form*/ }
<AddTodo submitHandler={submitHandler}></AddTodo>
<View style={styles.list}>
<FlatList
data={todos}
renderItem={({ item }) =>(
<TodoItem item={item} pressHandler={pressHandler}/>
)}
/>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
content:{
padding:40,
},
list: {
marginTop:20,
}
});
addTodo.js
import React, {useState} from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
export default function AddTodo({ submitHandler }) {
const [text, setText] = useState('');
const changeHandler = (val) => {
setText(val);
}
return (
<View>
<TextInput
style={styles.input}
placeholder='new todo...'
onChangeText={changeHandler}
/>
<Button onPress={() => submitHandler(text)} title='add todo' color='coral'></Button>
</View>
)
}
const styles = StyleSheet.create({
input :{
marginBottom:10,
paddingHorizontal: 8,
paddingVertical: 6,
borderBottomWidth:1,
borderBottomColor:'#ddd'
}
})
header.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default function Header() {
return (
<View style={styles.header}>
<Text style={styles.title}>My Todos</Text>
</View>
)
}
const styles = StyleSheet.create({
header:{
height:80,
paddingTop:38,
backgroundColor:'coral'
},
title: {
textAlign:'center',
color:'#fff',
fontSize:20,
fontWeight:'bold',
}
})
todoItem.js
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
export default function TodoItem({ item, pressHandler }){
return(
<TouchableOpacity onPress={() => pressHandler(item.key)}>
<Text style={styles.item}>{item.text}</Text>
</TouchableOpacity>
)
}
const styles = StyleSheet.create({
item:{
padding:16,
marginTop:16,
borderColor:'#bbb',
borderWidth:1,
borderStyle:'dashed',
borderRadius:10
}
})
반응형