본문 바로가기
앱 개발

[react-native] TouchableOpacity안에 Text 가운데 정렬하기

by evekang 2022. 5. 9.

내일배움카드로 스파르타 코딩클럽에서 열심히 앱개발 수업을 듣고 있다.

2주차 숙제를 하던 중에 막히는 부분을 발견했는데 

<TouchableOpacity>안에 <Text>를 썼는데 그 텍스트를 가운데로 정렬시키는 법에서 막혔다.

 

빨간 박스 안에 노란 버튼의 저 Text를 아래로 내리고 싶어 가운데로 맞추고 싶어...!!!!!!

 

 

 

우선 각 태그명

- 노란 박스 : button

- 안에 텍스트 : buttonText

 

우선 시도했던 방법1 : buttonText에 alignSelf: 'center' 넣기 → 실패

 button: {
        width: 150,
        height: 50,
        backgroundColor: '#F3B13E',
        borderRadius: 10,
        margin: 20,
        alignSelf: 'center'
    },
    buttonText: {
        borderWidth: 1,
        color: '#fff',
        fontWeight: 'bold',
        textAlign: 'center',
        alignSelf: 'center'
    }

 

그 다음 시도했던 방법2 : buttonText에 alignItems: 'center' 넣기 → 실패

    button: {
        width: 150,
        height: 50,
        backgroundColor: '#F3B13E',
        borderRadius: 10,
        margin: 20,
        alignSelf: 'center'
    },
    buttonText: {
        borderWidth: 1,
        color: '#fff',
        fontWeight: 'bold',
        textAlign: 'center',
        alignItems: 'center'
    }

 

아아닛 왜 안되는거야아아아아

구글링과 공식문서를 뒤져봐도 잘 모르겠다... 그런데 가만 보니 buttonText 안에서 아무리 정렬 해봤자 저 네모난 부분 안에서만 노는 것 같아서 정렬이 안 먹히는 것일수도 있겠다라는 생각이 들었다. 

그래서 buttonText에서 button으로 눈을 돌려 폭풍 검색을 했다. 

 

해결 방법 : button에 justifyContent: 'center' 넣기 → 성공!!!!

    button: {
        width: 150,
        height: 50,
        backgroundColor: '#F3B13E',
        borderRadius: 10,
        margin: 20,
        alignSelf: 'center',
        justifyContent: 'center'
    },
    buttonText: {
        borderWidth: 1,
        color: '#fff',
        fontWeight: 'bold',
        textAlign: 'center',
    }

 

justifyContent란?

justfiContent는 컨테이너의 주축 내에서 어린이를 정렬하는 방법을 설명합니다. 예를 들어, 이 속성을 사용하여 flexDirection이 행으로 설정된 컨테이너 내에서 수평으로 또는 flexDirection이 열로 설정된 컨테이너 내에서 수직 방향으로 하위를 이동할 수 있습니다. 

 

  • flex-start(기본값) : 컨테이너의 하위 항목을 컨테이너의 주 축 시작 부분에 맞춥니다.
  • flex-end : 컨테이너의 하위 항목을 컨테이너의 주 축 끝에 정렬합니다.
  • center : 컨테이너의 자식을 컨테이너 주축의 중앙에 정렬합니다.
  • space-between : 컨테이너의 주축을 가로질러 자식을 균등하게 간격을 두고 나머지 공간을 자식 사이에 분배합니다.
  • space-around : 컨테이너의 주축을 가로질러 자식을 균등하게 간격을 두고 나머지 공간을 자식 주위에 분산시킵니다. 공간 간극과 비교하여 공간 어라운드를 사용하면 첫째 자식의 시작과 마지막 자식의 끝 부분에 공간이 분배됩니다.

참고: 공식문서 https://reactnative.dev/docs/flexbox#justify-content

 

Layout with Flexbox · React Native

A component can specify the layout of its children using the Flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.

reactnative.dev

 

 

 

 

네.....?

뭐라고 하시는거애어

 

 

 

 

justifyContent는 flexDirection과 동일한 방향으로 정렬하는 속성이다.

 

flexDirection: 'column' 인 경우 justifyContent는 상하 정렬

flexDirection: 'row' 인 경우 justifyContent는 좌우 정렬

 

flexDirection: 'column'이 디폴트니까 justifyContent: 'center'가 먹힌 것 같다.

 

결과물은 아래처럼 예쁘게 가운데로 정렬되었다. 

아 숙제 끝났다!!!

반응형

댓글