최데브는 오늘도 프로그래밍을 한다.

리액트 네이티브 - 커스텀 버튼 만들기 본문

React

리액트 네이티브 - 커스텀 버튼 만들기

최데브 2020. 12. 16. 13:13
반응형

루트 폴더에 CustomButton.js 을 만들어준다.

기본적으로는 TouchableOpacity 를 뼈대로 만든다.

그냥 리액트의 button 은 아이폰과 안드로이드에서 보이는게 다를때가 많아서 

TouchableOpacity 로 만들면 통일감 있게 커스텀 버튼을 만들 수 있다고 한다.

 

버튼마다 크기나 색 , 타이틀이 달라야하니 Props 로 각 버튼의 스타일 정의를 넘겨받는다.

// CustomButton.js
import React, { Component } from 'react';
import {
  TouchableOpacity,
  Text,
  StyleSheet,
} from 'react-native';

export default class CustomButton extends Component{

    static defaultProps = {
        title: 'untitled',
        buttonColor: '#000',
        titleColor: '#fff',
        onPress: () => null,
      }

  constructor(props){
    super(props);
  }

  render(){
    return (
      <TouchableOpacity style={[
        styles.button,
        {backgroundColor: this.props.buttonColor}
      ]}
      onPress={this.props.onPress}>
        <Text style={[
          styles.title,
          {color: this.props.titleColor}
        ]}>{this.props.title}</Text>
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
    button: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        marginBottom: 10,
        borderRadius: 5,
      },
      title: {
        fontSize: 15,
      },
});

다음은 위 코드를 호출하는 App.js에서는

이런식으로 넣고싶은 View 안에다가 Props 를 넘겨주면 그 조건에 맞는 커스텀 버튼이 화면에 등장한다.

      <CustomButton
            buttonColor={'#023e71'}
            title={'로그인'}
            onPress={() => navigation.navigate('로그인')}/>

 

반응형
Comments