React-Native/[RN]Expo

[RN공부하기] [10]Todo App (part 3)

Dev갱이 2021. 11. 10. 08:31
728x90

클릭시 데이터 삭제구현까지 했다, 이제 데이터 추가 하는거까지 해보자!

//Components/Apptodo.jsx

import React,{ useState } from 'react'
import { View, StyleSheet, TextInput, Button } from 'react-native';

export default function AddTodo({SubmitHandler}) {
    const [text, setText] = useState('');

    const ChangeHandler = (val) => {
        setText(val);
    }
    return (
        <View>
            <TextInput
                style={styles.Inputs}
                placeholder='New To do...'
                onChangeText={ChangeHandler}
            >
            </TextInput>
            <Button onPress= { () => SubmitHandler(text)} title='Add todo' color='coral'></Button>
        </View>
    )
}

const styles = StyleSheet.create({
    Inputs: {
      marginBottom:10,
      paddingHorizontal :8,
      paddingVertical :6,
      borderBottomWidth : 1,
      borderBottomColor : '#ddd',
    }
});
//App.js
import { StatusBar } from 'expo-status-bar';
import React, { useState, useRef } from 'react';
import { View, StyleSheet } from 'react-native';
import FlatListComponents from './Components/FlatListComponents';
import ScrollViewComponent from './Components/ScrollViewComponent';


import Header from './Components/Header';
import Contents from './Components/Contents';
import AddTodo from './Components/AddTodo';
export default function App() {

  const nextId = useRef('7');

  const [todos, setTodos ] = useState([
      {todo: "Coding", key:'1' },
      {todo: "Shopping", key:'2' },
      {todo: "excyte", key:'3' },
      {todo: "movie", key:'4' },
      {todo: "wash", key:'5' },
      {todo: "cleaning", key:'6' },
      {todo: "Study", key:'7' },
  ]);
  
  const SubmitHandler = (text) => {
    nextId.current = parseInt(nextId.current)+1;
    
    /*
    setTodos( (prevTodos)=> {
      return [
        ...prevTodos,
        {todo: text, key : nextId.current.toString() }
        
      ];
    })
    */
    
    const newtodo = {
      todo: text,
      key : nextId.current.toString()
    };
    setTodos([...todos, newtodo]);
    
  }

  return (
    <View style={styles.container}>
      <Header></Header>
      <View style={styles.contents}>
        <AddTodo SubmitHandler={SubmitHandler}></AddTodo>
        <Contents todos={todos} setTodos={setTodos}></Contents>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  contents : {
    padding: 40,
  }
});

결과)

728x90