Text 컴포넌트

Tags
text
Column
 
"I am bold and red"
0-9: bold
9-17: bold, red
  • 단순히 텍스트를 출력하는 컴포넌트.
  • 중첩, 별도 스타일 적용, 터치 핸들링 다 가능하다.

코드 예시

import React, { useState } from "react"; import { Text, StyleSheet } from "react-native"; const onPressTitle = () => { console.log("title pressed"); }; const TextInANest = () => { const titleText = useState("Bird's Nest"); const bodyText = useState("This is not really a bird nest."); return ( {/* 텍스트 nesting 적용, 별도 스타일 적용, onPress로 터치 핸들링 */} <Text style={styles.baseText}> <Text style={styles.titleText} onPress={onPressTitle}> {titleText} {"\n"} {"\n"} </Text> <Text numberOfLines={5}>{bodyText}</Text> </Text> ); }; const styles = StyleSheet.create({ baseText: { fontFamily: "Cochin" }, titleText: { fontSize: 20, fontWeight: "bold" } }); export default TextInANest;
 

텍스트 중첩 예시 (스타일링 편의성)

  • Native에서는 NSAttributedString(ios) 또는 SpannableString(android)로 속성을 적용할 텍스트 범위를 명시해서 포맷팅하는데, 매우 번거로우므로 react-native에서는 텍스트 중첩으로 동일한 효과를 냄.
import React from 'react'; import { Text, StyleSheet } from 'react-native'; const BoldAndBeautiful = () => { return ( <Text style={styles.baseText}> I am bold <Text style={styles.innerText}> and red</Text> </Text> ); }; const styles = StyleSheet.create({ baseText: { fontWeight: 'bold' }, innerText: { color: 'red' } }); export default BoldAndBeautiful;
notion image
  • 위 코드는 Native로 변환 시 아래와 같이 변환된다.
    • NSAttributesString (ios)
    • SpannableString (android)
"I am bold and red" 0-9: bold 9-17: bold, red
 

컨테이너 비교 (View, Text)

  • View 컨테이너 내에 있는 Text 컴포넌트들은 Flexbox의 영향을 받아 각자 고유의 영역을 갖는다.
  • 하지만 Text 컨테이너 내에 있는 Text 컴포넌트들은 flexbox layout이 아닌 text layout을 적용받는다.
    • 줄바꿈 하기 전까지는 중첩해도 다 한줄로 표시됨.

View 컨테이너 (flexbox layout 적용)

<View> <Text>First part and </Text> <Text>second part</Text> </View>
notion image

Text 컨테이너 (text layout 적용)

<Text> <Text>First part and </Text> <Text>second part</Text> </Text>
notion image

스타일 중첩

공식 홈페이지 맨 하단쪽 참조
커스텀 텍스트 컴포넌트 만들기 포함.
 

스타일링

 
textDecorationLine
  • 밑줄 : textDecorationLine: 'underline'
  • 쉬소선 : textDecorationLine: 'line-through'