elevne's Study Note
React Native (4-1: RN 컴포넌트 알아보기(Text)) 본문
React Native 에서는, Web 과는 다르게 오직 Text 컴포넌트만이 텍스트 노드를 자식으로 가질 수 있다. 텍스트를 화면에 표시하기 위해서는 <Text> 컴포넌트로 모두 감싸주어야 한다는 뜻이다. RN 에서 Text 컴포넌트를 사용할 때는 Web 처럼 <strong>, <em> 같은 하위 태그를 사용할 수는 없으나, fontWeight 이나 fontStyle 등의 속성을 이용하여 비슷한 효과를 낼 수 있다. 아래와 같이 사용해볼 수 있다.
<Text>
The quick <Text style={{fontStyle: "italic"}}>brown</Text> fox jumped
over the lazy <Text style={{fontWeight:"bold"}}>dog</Text>.
</Text>
단, 위처럼 모든 style 을 inline 형태로 적는 것보다 아래와 같이 따로 styles 객체 안에 넣어주는 것이 사용하기 간편하다.
const styles = StyleSheet.create({
bold: {
fontWeight: "bold"
},
italic: {
fontStyle: "italic"
}
})
또, 더욱 간편하게 하기 위해서 이를 하나의 컴포넌트로 아래와 같이 작성하여 사용할 수도 있다.
import { useState } from "react";
import { StyleSheet, Text } from "react-native";
const Test = () => {
const [val, setVal] = useState(null)
return (
<Text>
The quick <Em>brown</Em> fox jumped
over the lazy <Strong>dog</Strong>.
</Text>
)
}
const styles = StyleSheet.create({
bold: {
fontWeight: "bold"
},
italic: {
fontStyle: "italic"
}
})
const Em = ({children}) => {
return (
<Text style={styles.italic}>
{children}
</Text>
)
}
const Strong = ({children}) => {
return (
<Text style={styles.bold}>
{children}
</Text>
)
}
export default Test;
일반적으로 RN 에서 스타일이 적용된 텍스트를 다룰 때는 웹개발과는 다르게 접근해야 한다. Style 은 하위노드에게 상속되지 않기 때문에 트리에 속한 모든 텍스트 노드에 적용되는 기본 폰트를 적용할 수 없다고 한다. 그래서 RN 문서에서도 이러한 문제를 스타일이 적용된 컴포넌트를 직접 만들어 해결할 것을 권고한다.
Reference:
빠른 모바일 앱 개발을 위한 React Native
'Frontend > React Native' 카테고리의 다른 글
React Native (4-3: RN 컴포넌트 알아보기(Button, TouchableHighlight, Pressable)) (0) | 2023.02.21 |
---|---|
React Native (4-2: RN 컴포넌트 알아보기(Image)) (0) | 2023.02.20 |
React Native (3-2: RN 날씨앱 만들어보기) (0) | 2023.02.18 |
React Native (3-1: RN 날씨앱 만들어보기) (0) | 2023.02.14 |
React Native (2: RN 개발환경 구축) (0) | 2023.02.13 |