반응형

 

버튼으로 사용할 수 있는 것은

Button과 TouchableOpacity

이렇게 두가지가 있습니다.

이번시간에는 두가지의 차이점이 무엇인지 

또 사용방법이 어떻게 되는지 알아보도록 하겠습니다.

 

 

Button

버튼은 말 그대로 버튼의 역할을 수행합니다.

다음의 예제 코드를 확인해봅시다

import React from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';

export default function App() {

  const customAlert = () => {        //alert를 띄우는 함수 선언
    Alert.alert("버튼알람 입니다!") 
  }

  return (
    <View style={styles.container}>
      <View style={styles.textContainer}>
        <Button                             //버튼 생성
          style={styles.buttonStyle} 
          title="버튼입니다 "
          color="blue" 
          onPress={customAlert}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  textContainer: {
    height:100,
    margin:10,
  },
  textStyle: {
    textAlign:"center"
  },
});

버튼이 눌러졌을때의 처리도 onpress를 이용해 사용할 수 있습니다.

 

 

 

TouchableOpacity

TouchableOpactiy는 클릭할 수 있는 작은 View라고 생각하면 됩니다.

여기에는 글자도 가능하며, 이미지또한 사용이 가능합니다.

버튼과 가장큰 차이점은 여러가지 속성을 지정할 수 있습니다.

 

아래는 예제입니다.

import React from 'react';
import { StyleSheet, Text, View, ScrollView, TouchableOpacity, Alert, justifyContent } from 'react-native';

export default function App() {
  const customAlert = () => {
    Alert.alert("버튼알람 입니다.")
  }
  return (
    <ScrollView style={styles.container}>
      <TouchableOpacity style={styles.textContainer} onPress={customAlert}>
        <Text style={styles.textStyle}>TouchableOpacity 예제입니다.</Text>
      </TouchableOpacity>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff'
  },
  textContainer: {
    height:100,
    borderColor:'#000',
    borderWidth:10,
    borderRadius:40,
    margin:10,
    justifyContent:"center",
    marginTop:30
  },
  textStyle: {
    textAlign:"center",
    fontSize:22
  }
});

TouchableOpacity 출력 예
실행 결과

 

 

실행 결과와 같이 큰 버튼 형식으로 출력되는걸 볼 수 있습니다.

Button보다 세세한 설정이 가능하므로 

TouchableOpacity가 더 널리 사용되는 편입니다.

 

 

반응형

+ Recent posts