Touchable Component

旅人·2023년 3월 25일
0

button이 아닌 다른 컴포넌트에 button과 같이 터치했을 때

이벤트 등의 효과를 주고 싶으면 Touchable 컴포넌트를 사용

네이티브 컴포넌트인 button 보다 유동적

또한, button은 안드로이드와 iOS환경에서 다르게 보일 수 있다고 한다.

(하지만 최근에 Pressable 컴포넌트가 등장해서 이쪽이 확장성이 높아 더 권장되는 추세인듯)


터치했을 때 컴포넌트의 opaque 효과(터치했을 때희미해짐)를 줄 수 있는 TouchableOpacity를 사용

터치한 컴포넌트가 사라지도록 했음

공식 HP : https://reactnative.dev/docs/touchableopacity

Code

import {
  StyleSheet,
  Text,
  View,
  FlatList,
  TouchableOpacity,
} from "react-native";
import React, { useState } from "react";

export default function App() {
  const [people, setPeople] = useState([
    { name: "A", id: "1" },
    { name: "B", id: "2" },
    { name: "C", id: "3" },
    { name: "D", id: "4" },
    { name: "E", id: "5" },
    { name: "F", id: "6" },
    { name: "G", id: "7" },
    { name: "H", id: "8" },
    { name: "I", id: "9" },
    { name: "J", id: "10" },
    { name: "K", id: "11" },
    { name: "L", id: "12" },
    { name: "M", id: "13" },
    { name: "N", id: "14" },
  ]);

  const pressHandler = (id) => {
    // console.log(id);
    setPeople(people.filter((person) => person.id != id));
  };

  return (
    <View style={styles.container}>
      <FlatList
        numColumns={2}
        keyExtractor={(item) => item.id}
        data={people}
        renderItem={({ item }) => (
          <TouchableOpacity onPress={() => pressHandler(item.id)}>
            <Text style={styles.item}>{item.name}</Text>
          </TouchableOpacity>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    // alignItems: "center",
    // justifyContent: "center",
    paddingTop: 40,
    paddingHorizontal: 20,
  },
  item: {
    marginTop: 24,
    padding: 30,
    backgroundColor: "pink",
    fontSize: 24,
    marginHorizontal: 10,
    marginTop: 24,
  },
});

실행화면

  • A를 클릭해서 삭제


참고 :

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

https://velog.io/@beanlove97/Pressable-vs.-Touchable-in-React-Native

https://jcon.tistory.com/147

profile
一期一会

0개의 댓글