본문 바로가기

Study/React-Native

[React-Native] 기본 태그 종류 (View, Text, Image 등)

React-Native를 통한 개발은 처음이라 개발에 들어가기 전 조금이라도 친숙해지기 위해 주로 사용되는 기본 태그들에 대해 살펴보았다.

 

React Native의 주요 태그 정리🙄

View

  • React-Native에서 UI를 구축하는 가장 기본적인 구성 요소
  • html의 <div> 태그와  유사한 역할을 함
  • View 안에 여러 View가 올 수 있음 (중첩 가능)
  • View 내부에 텍스트 컴포넌트가 아닌 텍스트 노드가 위치할 수 없음
import { View, Text } from 'react-native';

const MyComponent = () => {
  return (
    <View>
      <Text>Hello, React Native!</Text>
    </View>
  );
};

/**=======================================*/
// View 태그에 텍스트 노드가 바로 올 수 없음
// BAD: will raise exception, can't have a text node as child of a <View>
<View>
  Some text
</View>

// GOOD
<View>
  <Text>
    Some text
  </Text>
</View>

Text

  • 텍스트를 표시하기 위한 컴포넌트
  • html의 <p>, <span> 태그와  유사한 역할을 함
  • Text 컴포넌트도 중첩이 가능함
    • 부모 Text의 스타일을 상속받으면서 텍스트의 일부분만 다른 스타일을 적용하고 싶을 때
    • React Native는 중첩된 Text 컴포넌트를 내부적으로 하나의 네이티브 텍스트 요소로 최적화됨
    • 중첩된 텍스트가 하나의 연속된 흐름으로 처리됨 (줄바꿈, 공백 처리가 달라짐)
import { View, Text } from 'react-native';

const MyComponent = () => {
  return (
    <View>
      <Text style={{fontWeight: 'bold'}}>
        This text is bold
        <Text style={{color: 'red'}}>and this is bold and red</Text>
      </Text>
    </View>
  );
};
/**=============================================================*/
// 중첩 유/무에 따른 레이아웃 결과
// |First part and second part| 
<Text>
  <Text>First part and </Text>
  <Text>second part</Text>
</Text>

// |First part and|
// |second part   | 
<View>
  <Text>First part and </Text>
  <Text>second part</Text>
</View>
  • 알아두면 좋은 Props
    • numberOfLines : 지정된 줄 수를 초과하면 이후 텍스트 잘림
      • <Text numberOfLines={2}> This is a long text that will be truncated after two lines... </Text>
    • ellipsizeMode : 텍스트가 어떻게 잘릴지 정의
      • <Text numberOfLines={2} ellipsizeMode="tail" > This is a long text, maximum is two... </Text>
        • head : 초과 시 시작 부분을 ...으로 줄임 / "...xyz"
        • middle : 초과시 중간에 누락된 텍스트를 ...으로 줄임 / "ab...yz"
        • tail : 초과 시 마지막 부분을 ...으로 줄임 / "abcd..."
        • clip : ...을 사용하지 않고 초과된 텍스트 보이지 않음 "abcd"
    • selectionColor : 텍스트를 블록 선택했을 때 나타나는 하이라이트 색상 (드래그 시 배경 색)
      • <Text selectionColor="yellow"> This text will have a yellow highlight when selected </Text>

TextInput

  • 텍스트를 입력하기 위한 컴포넌트
  • html의 <input type="text"> 태그와  유사한 역할을 함
import { View, TextInput } from 'react-native';

const MyComponent = () => {
  return (
    <View>
        <TextInput
          onChangeText={onChangeNumber}
          value={number}
          placeholder="this is placeholder"
        />
    </View>
  );
};
  • 알아두면 좋은 Props
    • value : 텍스트 입력의 현재 값 설정
    • onChangeText (function): 텍스트가 변경될 때 호출되는 콜백
    • placeholder (string) : 텍스트가 입력되기 전 미리 보여줄 문자열
    • secureTextEntry (bool) : 패스워드같은 민감한 정보를 입력할 때 텍스트를 점이나 별표로 대체
    • inputMode/keyboardType (enum) : 텍스트 입력 시 기본 키보드 유형 지정
      • inputMode가 keyboardType보다 우선순위가 높음
      • inputMode: 웹 앱과 iOS, Android 모두에서 일관되게 작동  
      • inputMode Enum : 'decimal', 'email', 'none', 'numeric', 'search', 'tel', 'text', 'url'
      • keyboardType :네이티브 앱에 특화되어 있어플랫폼별 키보드 타입을 지정
      • keyboardType Enum : 'default', 'email-address', 'numeric', 'phone-pad', 'ascii-capable' ...
    • multiline (bool): 여러줄 입력 허용 여부, default: false
      • + numberOfLines (number) : multiline이 true일 때 표시할 줄 수를 지정 (only Android)
    • maxLength (number) : 입력 가능한 최대 문자 수 지정
    • editable (bool) : 편집 가능 여부 설정

Image

  • 다양한 유형의 이미지를 표시하기 위한 컴포넌트
  • html의 <img> 태그와  유사한 역할을 함
  • 자체 네이티브 코드 빌드 시 Android에서 GIF, WebP를 기본적으로 지원하지 않아 build.gradle에 모듈 추가 작업 필요
import { View, Image } from 'react-native';

const MyComponent = () => {
  return (
    <View>
      <Image
        source={require('./path/to/image.jpg')}
        style={{width: 200, height: 200}}
      />
    </View>
  );
};
  • 알아두면 좋은 Props
    • source : 이미지 소스 지정
      • source={{uri: 'https://example.com/image.jpg'}}
      • source ={require('@expo/snack-static/react-native-logo.png')}
      • source ={{
                  uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==',
                }}