컴포넌트를 공부하면서 주요하게 기억해야할 항목들을 메모하자
StyleSheet : 컴포넌트에 스타일 적용
[CSS와 주요 차이점]
1. 셀렉터 없음
2. camelCase로 작성
3. display 속성은 기본적으로 flex, 다른 값은 none 밖에 없음
4. flexDirection 속성 기본값 : 웹에서는 row, 하지만 리액트 네이티브에선 column
5. 숫자 단위 : dp
6. background 대신 backgroundColor
7. border 대신 borderWidth, borderStyle, borderColor 따로 설정 필요
[예제 코드]
import React from 'react';
import {View, StyleSheet} from 'react-native';
function Box() {
return <View style={styles.box} />;
}
const styles = StyleSheet.create({
box: {
width: 64,
height: 64,
backgroundColor: 'black',
},
});
export default Box;
StyleSheet : 고급 적용
[동시에 여러 스타일 적용]
<View style={[styles.box, styles.rounded]} />
[props가 true일 때만 스타일 적용]
import React from 'react';
import {View, StyleSheet} from 'react-native';
function Box(props) {
return <View style={[styles.box, props.rounded && styles.rounded]} />
}
(...)
// 호출 구문
<Box rounded={true} />
// 혹은
<Box rounded />
[전체 영역 사용]
flex 스타일 속성값 1로 설정
const App = () => {
return (
<SafeAreaView style={styles.full}>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
full: {
flex: 1,
},
});
Props 객체 구조 분해 할당
객체 안에 있는 값을 더욱 짧은 코드를 사용해 밖으로 추출(비구조화 할당)
[예시]
function print(params) {
console.log(params.name);
console.log(params.description);
}
function print(name, description) {
console.log(name);
console.log(description);
}
-> 위 두 구문은 기능적으로 동일함
[Component에 적용]
function Box({rounded, size, color}) {
return (
<View
style={[
styles.box,
rounded && styles.rounded,
sizes[size],
{
backgroundColor: color,
},
]}
/>
);
}
useState Hook으로 상태 관리
동적인 UI 관리를 위한 변수 상태 관리 : useState 함수 사용
※ Hook : 리액트에서 제공하는 use로 시작하는 다양한 상태 관리 함수
[함수 불러오기]
import React, {useState} from 'react';
[함수 사용하기]
const [count, setCount] = useState(0);
※ 구조 분해 할당에 의해 count에는 0, setCount에는 count 상태값을 변경할 수 있는 함수가 할당됨
[Hook 규칙]
1. 컴포넌트 최상위 레벨에서만 사용
즉, 조건문이나 반복문 또는 중첩 함수에서 호출 불가
2. Custom Hook : 직접 만들어 쓰는 Hook
3. Hook은 Custom Hook 또는 함수 컴포넌트에서만 사용 가능(클래스에서는 사용 불가, 일반 자바스크립트 함수에서 사용 불가)
[사용 예제]
import React, {useState} from 'react';
import {SafeAreaView, Button} from 'react-native';
import Box from './components/Box';
const App = () => {
const [visible, setVisible] = useState(true);
const onPress = () => {
setVisible(!visible);
}
return (
<SafeAreaView>
<Button title="토글" onPress={onPress} />
{visible && <Box color="blue" />}
</SafeAreaView>
);
};
export default App;
'React Native' 카테고리의 다른 글
React Native) Component 활용하기 - 2 (0) | 2023.07.23 |
---|---|
React Native) flex 레이아웃 (0) | 2023.07.23 |
React Native) Component 활용하기 - 1 (0) | 2023.07.21 |
React Native 컴포넌트 개념 잡기 - 1 (0) | 2023.07.19 |
React Native 시작하기 (0) | 2023.07.16 |