react native todo 수정,삭제
삭제
alert로 취소,삭제 버튼을 준 후 삭제를 누르면 실행
alert문법은 Alert.alert("제목", "내용", [{ text:"버튼1", style: "3가지" }, { text:"버튼2", style: "3가지" }]);
아래 코드에서 onPress로 todo.id를 매개변수로 준다. 매개변수를 id로 받아서 filter를 이용해 todos안의 todo.id와 같지 않은 것만 출력
const deleteTodo = (id) => {
//alert쓰는 방식 제목,내용을 쓰고 버튼은 배열안에 객체를 넣어서 씀 style로 세가지 모양가능
Alert.alert("Todo 삭제", "정말 삭제하시겠습니까?", [
{
text: "취소",
style: "cancel",
},
{
text: "삭제",
style: "destructive",
onPress: () => {
//1. id 값을 받아서 해당 배열 요소를 제외한 나머지 를 새로운 배열로 받는다.
//2. setTodos
const newTodos = todos.filter((todo) => todo.id !== id);
//todo.id와 매개변수로 받은 id가 같지 않은 것만 출력해라.
setTodos(newTodos);
},
},
]);
};
<AntDesign
name="delete"
size={20}
color="black"
onPress={() => deleteTodo(todo.id)}
/>
수정
수정도 마찬가지로 아래 코드블럭에서 todo.id를 매개변수로 준 후 id로 받아와 findIndex로 대상을 찾는다.
찾은 후 isEdit속성을 반대로 바꿔준다.
const setEdit = (id) => {
const newTodos = [...todos];
const idx = newTodos.findIndex((todo) => todo.id === id);
//주어진 함수를 통과한 첫번째만 찾는 findindex로 대상아이디 식별
newTodos[idx].isEdit = !newTodos[idx].isEdit;
//isDone을 true혹은 false로 변환
setTodos(newTodos);
setEditText("");
};
<TouchableOpacity onPress={() => setEdit(todo.id)} />
isEdit가 true면 수정TextInput이 나타나게 하고 아니면 글(todo.text)이 나타나게 한다.
editText useState를 만들고 onChangeText로 setEditText를 변경한다
{todo.isEdit ? (
<ContentTextInput
onSubmitEditing={() => editTodo(todo.id)}
onChangeText={setEditText}
value={editText}
placeholder="Enter your task"
/>
) : (
<ContentText
style={{
textDecorationLine: todo.isDone ? "line-through" : "none",
}}
>
{todo.text}
</ContentText>
)}
위에 코드 수정에서 똑같이 id를 줘서 대상을 식별하고 idx변수로 지정한다.
newTodos[idx]를 지정한 후 .text를 setEditText로 바꾼 editText로 교체한다.
교체되면 isEdit은 다시 false로 돌아와 글로 보이게 한다.
const [editText, setEditText] = useState("");
const editTodo = (id) => {
//1. id 값 받아서 해당 배열의 요소를 찾는다. idx 찾기
//2. todos[idx].text = editText;
const newTodos = [...todos];
const idx = newTodos.findIndex((todo) => todo.id === id);
newTodos[idx].text = editText;
newTodos[idx].isEdit = false;
setTodos(newTodos);
};