5) React-Native 이벤트

1. press 이벤트

버튼을 만들 때 사용하는 TouchableOpactiy 컴포넌트에서 설정할 수 있는 Press 이벤트의 종류는 총 4가지이다.

  • onPressIn: 터치가 시작될 때 항상 호출
  • onPressOut: 터치가 해제될 때 항상 호출
  • onPress: 터치가 해제될 때 onPressOut 이후 호출
  • onLongPress: 터치가 일정 시간 이상 지속되면 호출

src/components/EvenetButton.js

import React from "react";
import { TouchableOpacity, Text } from "react-native";

const EventButton = () => {
  const _onPressIn = () => console.log("Press In !!!\\n");
  const _onPressOut = () => console.log("Press out !!!\\n");
  const _onLongPress = () => console.log("Long Press !!!\\n");
  const _onPress = () => console.log("Press !!!\\n");
  return (
    <TouchableOpacity
      style={{
        backgroundColor: "#3498db",
        padding: 16,
        margin: 10,
        borderRadius: 8,
      }}
      onPressIn={_onPressIn}
      onLongPress={_onLongPress}
      onPressOut={_onPressOut}
      onPress={_onPress}
    >
      <Text style={{ color: "white", fontSize: 24 }}>Press</Text>
    </TouchableOpacity>
  );
};

export default EventButton;

src/App.js

import React from "react";
import { View, Text } from "react-native";
import Counter from "./components/Counter";
import EventButton from "./components/EventButton";

const App = () => {
  return (
    <View
      style={{
        flex: 1,
        backgroundColor: "#fff",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <EventButton />
    </View>
  );
};

export default App;

화면에서 버튼을 클릭하면

  • onPressIn → onPressOut → onPress
  • onPressIn → onLongPress → onPressOut

onPressIn과 onPressOut은 항상 호출되지만, onPress와 onLongPress는 사용자가 클릭하는 시간에 따라 둘 중 하나만 호출된다.

onLongPress가 호출되는 시간을 조절하고 싶다면, delayLongPress의 값을 조절해서 원하는 시간으로 설정할 수 있다.

const EventButton = () => {
  const _onPressIn = () => console.log("Press In !!!\\n");
  const _onPressOut = () => console.log("Press out !!!\\n");
  const _onLongPress = () => console.log("Long Press !!!\\n");
  const _onPress = () => console.log("Press !!!\\n");
  return (
    <TouchableOpacity
      style={{
        backgroundColor: "#3498db",
        padding: 16,
        margin: 10,
        borderRadius: 8,
      }}
      onPressIn={_onPressIn}
      onLongPress={_onLongPress}
      onPressOut={_onPressOut}
      onPress={_onPress}
      delayLongPress={3000}
    >
      <Text style={{ color: "white", fontSize: 24 }}>Press</Text>
    </TouchableOpacity>
  );
};

delayLongPress={3000}을 추가하면 3초동안 클릭하고 있어야 onLongPress가 호출된다.

2. change 이벤트

TextInput 컴포넌트를 이용하여 변화하는 텍스트를 출력ㅎ보자

src/components/EventInput.js

import React, { useState } from "react";
import { View, Text, TextInput } from "react-native";

const EventInput = () => {
  const [text, setText] = useState("");
  const _onChange = (event) => setText(event.nativeEvent.text);

  return (
    <View>
      <Text style={{ margin: 10, fontSize: 30 }}>text: {text}</Text>
      <TextInput
        style={{ borderWidth: 1, padding: 10, fontSize: 20 }}
        placeholder="Enter a text..."
        onChange={_onChange}
      ></TextInput>
    </View>
  );
};
export default EventInput;

이렇게 하게 되면

{

	…..,

	“nativeEvent” : {

		“eventCount”: …,

		“target”: …,

		“text”: …,

	},

	…..

}

이런 식으로 인자를 전달하기에 text를 뽑아 써야 한다.

하지만 이것을 더 쉽게 구현할 수 있다

import React, { useState } from "react";
import { View, Text, TextInput } from "react-native";

const EventInput = () => {
  const [text, setText] = useState("");
  const _onChangeText = (text) => setText(text);

  return (
    <View>
      <Text style={{ margin: 10, fontSize: 30 }}>text: {text}</Text>
      <TextInput
        style={{ borderWidth: 1, padding: 10, fontSize: 20 }}
        placeholder="Enter a text..."
        onChangeText={_onChangeText}
      ></TextInput>
    </View>
  );
};
export default EventInput;

3. Pressable 컴포넌트

Pressable 컴포넌트에서 지원하는 기능 중 기존의 컴포넌트들과 다른 특징은 HitRect와 PressRect이다.

버튼을 정확하게 클릭하는 것이 어려울 수 있다, 따라서 버튼 모양보다 약간 떨어진 부분까지 이벤트가 발생할 수 있도록 HitRect을 이용해 이 설정을 쉽게 할 수 있다.

버튼을 누른 상태에서 손가락을 이동시키면 어떻게 처리를 할까?

Pressable 컴포넌트에서는 이 부분을 개발자가 조절하기 편하도록 PressRect기능을 지원한다.

import { Pressable, StyleSheet, Text, View } from "react-native";
import React from "react";

const Button = (props) => {
  return (
    <Pressable
      style={{ padding: 10, backgroundColor: "#1abc9c" }}
      onPressIn={() => console.log("Press In")}
      onPressOut={() => console.log("Press Out")}
      onPress={() => console.log("Press")}
      onLongPress={() => console.log("Long Press")}
      delayLongPress={3000}
      pressRetentionOffset={{ bottom: 50, left: 50, right: 50, top: 50 }}
      hitSlop={50}
    >
      <Text style={{ padding: 10, fontSize: 30 }}>{props.title}</Text>
    </Pressable>
  );
};

const App = () => {
  return (
    <View
      style={{
        flex: 1,
        backgroundColor: "#fff",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <Button title="Pressable" />
    </View>
  );
};
export default App;

이렇게 구현하게 되면 버튼에서 조금 떨어져 있어도 클릭되고, 버튼을 누른 상태에서 이동했을 때 항상 같은 위치에서 onPressOut이 호출되는 것을 확인할 수 있다.

'React-Native' 카테고리의 다른 글

6) React-Native 스타일링  (4) 2024.10.24
4) React-Native Props와 State  (0) 2024.10.23
3) React-Native 컴포넌트  (0) 2024.10.23
2) React-Native JSX  (0) 2024.10.23
1) 리액트 네이티브란  (4) 2024.10.23