터치 핸들링 하기
카테고리: ReactNative
업데이트:
기본적인 버튼에서 터치를 핸들링 하는 방법은 다음과 같습니다.
const MyComponent = () => {
return (
<View>
<Button
title="페이지 이동"
onPress={() =>
alert("이곳에 press에 대한 기능을 구현하면 됩니다.")
}
/>
</View>
);
};
하지만 기본 버튼이 앱에 안 맞는 경우 React Native에서 제공하는 Touchable 컴포넌트를 사용해 고유한 버튼을 만들 수 있습니다.
또는 제스처를 인식하는 기능을 제공해 제스처에 대한 핸들링 또한 가능합니다.
Touchable의 종류는 다음과 같습니다.
-
TouchableHighlight : 사용자가 컴포넌트를 터치할 때 색이 연해집니다.
-
TouchableOpacity : 사용자가 컴포넌트를 터치할 때 색이 투명해집니다.
-
TouchableWithoutFeedback : 사용자가 컴포넌트를 터치할 때 변화가 없습니다.
사용법은 다음과 같습니다.
```javascript class MyComponent extends React.Component { _onPressButton() { alert(‘버튼 클릭!’) }
_onLongPressButton() {
alert('버튼 길게 클릭!')
}
render() {
return (
<View style={styles.container}>
{/* 사용자가 컴포넌트를 터치할 때 색이 연해집니다. */}
<TouchableHighlight
onPress={this._onPressButton}
onLongPress={this._onLongPressButton}
underlayColor="white"
>
<View style={styles.button}>
<Text style={styles.buttonText}>TouchableHighlight</Text>
</View>
</TouchableHighlight>
{/* 사용자가 컴포넌트를 터치할 때 색이 투명해집니다. */}
<TouchableOpacity
onPress={this._onPressButton}
onLongPress={this._onLongPressButton}
>
<View style={styles.button}>
<Text style={styles.buttonText}>TouchableOpacity</Text>
</View>
</TouchableOpacity>
{/* 사용자가 컴포넌트를 터치할 때 변화가 없습니다. */}
<TouchableWithoutFeedback
onPress={this._onPressButton}
onLongPress={this._onLongPressButton}
>
<View style={styles.button}>
<Text style={styles.buttonText}>TouchableWithoutFeedback</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
} };
댓글남기기