기본적으로 스타일은 컴포넌트에 인라인 방식으로 적용한다.
<View style={{ marging: 16 }}></View>
StyleSheet 객체를 사용하여 스타일 코드 작성 후 인라인으로 전달한다.
JSX 코드와 style 코드를 완벽히 분리하며, 코드의 재사용이 용이
import { StyleSheet, Text, View } from 'react-native';
const HelloWorld = () => {
return (
<View style={styles.container}>
<Text style={styles.hello}>Hello, World</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
hello: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
style객체의 배열을 전달 할 수 있다.
style속성으로 스타일 객체가 담긴 배열을 전달하면 전달 된 모든 스타일을 적용한다.
export default const MyComponent = ({ customStyle }: Props) => {
return (
<View style={[style.container, customStyle?.container]}>
...
</View>
);
};
const style = StyleSheet.create({
container: {
...
}
});
React Native에는 css가 존재하지 않으나, 스타일 코드 작성 규칙은 CSS의 영향을 받아 만들어져 CSS와 속성이 유사하지만 완전히 동일하지 않음.
// ❌Error! border 속성은 존재하지 않음.
<View style={{ border: "1px solid black" }}></View>
// ✅correct!
<View style={{ borderWidth: 1, borderColor: "#000" }}></View>
<View\>
컴포넌트는 기본적으로 display: flex
flexDirection: column
가 설정 되어있음
<Text>
컴포넌트를 감싸는 부모요소에 폰트 관련 스타일을 적용해도 하위로 상속이 이루어지지 않음.
// React - 부모 요소에 폰트 관련 스타일 적용 시 자식 요소에 상속 됨
<div style={{color: "blue"}}>
<p>Hello World</p> // textColor가 파란색으로 출력 됨
</div>
// ReactNative - 부모 요소에 적용 된 폰트 스타일이 상속되지 않음.
<View style={{color: "blue"}}>
<Text>Hello World</Text> // textColor가 적용되지 않음
</View>
Text의 색상을 변경하기 위해서 컴포넌트에 직접 스타일을 입혀야한다.
<View>
<Text style={{color: "blue"}}>Hello World</Text>
</View>
단, <Text>
컴포넌트를 중첩으로 사용하는 경우 상속 가능
<Text style={{color: "blue"}}>
<Text>Hello World</Text> // textColor가 파란색으로 출력 됨
</Text>
<ScrollView\>
컴포넌트를 활용한다.<View style={{height: "300px"}}>
<ScrollView>
...
</ScrollView>
</View>
파일명.운영체제.ts
로 생성한다.MyComponent.android.ts
MyComponent.ios.ts
import MyComponent from './component'