Alert, Keyboard(dismiss)

旅人·2023년 3월 26일
0

Alert

지난 번에 만든 todo 에서

글자 수가 3이하일 경우 alert를 띄우게 하기

alert의 매개 변수를 설정하여 제목, 메시지, 확인 버튼, 확인 버튼 터치 후 실행할 명령 등을 지정 가능

Keyboard(dismiss)

그리고 입력을 하려다가 다른 부분을 터치해서 키보드를 종료시키고 싶을 경우가 있다.

전체 컴포넌트를 TouchableWithoutFeedback으로 감싸고

onPress 이벤트의 콜백함수로 Keyboard.dismiss()를 주자.

TouchableWithoutFeedback은 자식 컴포넌트의 이벤트가 발생했을 때 아무런 효과도 주지 않게 하기 위해 쓴다고 함.

키보드 켜놓고 다른 부분을 터치해서 키보드를 없애려고 하는데

만약에 이벤트가 걸려있는 부분을 눌러서 이벤트가 실행되는 것을 막으려고 하는 듯

공식 HP : https://reactnative.dev/docs/touchablewithoutfeedback
기타 : https://daesiker.tistory.com/32


Code

import {
  StyleSheet,
  Text,
  View,
  FlatList,
  Alert,
  TouchableWithoutFeedback,
  Keyboard,
} from "react-native";
import React, { useRef, useState } from "react";
import Header from "./components/header";
import TodoItem from "./components/todoItem";
import AddTodo from "./components/addTodo";

export default function App() {
  const [todos, setTodos] = useState([
    { text: "Javascript", key: "1" },
    { text: "Python", key: "2" },
    { text: "C#", key: "3" },
    { text: "Ruby", key: "4" },
    { text: "Kotlin", key: "5" },
    { text: "Swift", key: "6" },
    { text: "Java", key: "7" },
  ]);

  const size = todos.length;
  const nextId = useRef(size);

  const pressHandler = (key) => {
    setTodos((prevTodos) => prevTodos.filter((todo) => todo.key != key));
  };

  const submitHandler = (text) => {
    if (text.length > 3) {
      nextId.current++;

      setTodos((prevTodos) => [
        ...prevTodos,
        { text: text, key: nextId.current.toString() },
      ]);
    } else {
      Alert.alert("OOPS!", "Todos must be over 3 chars long.", [
        { text: "UnderStood", onPress: () => console.log("alert closed") },
      ]);
    }
  };

  return (
    <TouchableWithoutFeedback
      onPress={() => {
        Keyboard.dismiss();
      }}
    >
      <View style={styles.container}>
        {/* header */}
        <Header />
        <View style={styles.content}>
          {/* to from */}
          <AddTodo submitHandler={submitHandler} />
          <View style={styles.list}>
            <FlatList
              data={todos}
              renderItem={({ item }) => (
                <TodoItem item={item} pressHandler={pressHandler} />
              )}
            />
          </View>
        </View>
      </View>
    </TouchableWithoutFeedback>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    // alignItems: "center",
    // justifyContent: "center",
  },
  content: {
    padding: 40,
  },
  list: {
    marginTop: 20,
  },
});

실행화면

  • 초기

  • 입력 글자수 3이하일 때


참고 :

https://www.youtube.com/watch?v=oVA9JgTTiT0&list=PL4cUxeGkcC9ixPU-QkScoRBVxtPPzVjrQ&index=12

https://www.youtube.com/watch?v=IW-SEiRjUsI&list=PL4cUxeGkcC9ixPU-QkScoRBVxtPPzVjrQ&index=13

profile
一期一会

0개의 댓글