useState 사용하여 데이터 추가 및 삭제하기
import React,{useState} from 'react'
const I= () =>{
const [names, setNames]=useState([
{id: 1, text: "snowman"},
{id: 2, text: "ice"},
{id: 3, text: "snow"},
{id: 4, text: "windy"}
])
const [inputText,setInputText]=useState('')
const [nextId,setNextId]=useState(5)
{/*1.input에 데이터를 넣었을 때 text가 추가되어야 한다. */ }
const onChange= (e)=>setInputText(e.target.value)
{/*2.추가 버튼을 눌렀을 때 기존에 names에 데이터가 추가 되어야 하는 onClick함수 선언 */ }
const onClick=()=>{
const nextNames= names.concat({
id: nextId,
text: inputText
})
setNextId(nextId+1)
setNames(nextNames)
setInputText('')
}
{/* 그 열을 더블 클릭했을 때 사라지게 하는 event를 만들어 보자 */}
const onRemove = id => {
const nextNames = names.filter(name=> name.id !== id)
setNames(nextNames)
}
const namesList= names.map(names =><li key={names.id} onDoubleClick={()=>onRemove(names.id)}>{names.text}</li> )
return(
<>
<input type="text" value={inputText} onChange={onChange}/>
<button onClick={onClick}>추가</button>
<li>{namesList}</li>
</>
)
}
'리액트' 카테고리의 다른 글
react 의 원리 (0) | 2021.12.09 |
---|---|
react 새로운 tweet 추가 방법 공부 (0) | 2021.09.27 |
useState #2 숫자 데이터 count하기 (0) | 2021.09.08 |
react 처음 시작할 때!! 참고 (0) | 2021.09.02 |