Illie
React Native. Props로 컴포넌트 스타일을 커스터마이징하기 본문
개요
버튼 하나를 커스터마이징 잘하면, 쓸 때마다 꺼내쓸 수 있다
하지만 익숙치 않아서 난관을 겪고 있다
큰일났다
기본 예제
Box.js에서 style을 자체적으로 생산해내는 아래와 같은 예제가 있다
// App.js
<Box />
// Box.js
<View styles={[styles.box, styles.rounded]} />
const styles = StyleSheet.create({
box: {
width: 32,
height: 32,
backgroundColor: 'red',
},
rounded: {
borderRadius: 16,
},
})
이를 prop를 활용하여 커스터마이징 해보자
1. Round 커스터마이징
// App.js
<Box rounded />
- 삼항연산자 사용
// Box.js
<View styles={[styles.box, props.rounded ? styles.rounded : null ]} />
const styles = StyleSheet.create({
box: {
width: 32,
height: 32,
backgroundColor: 'red',
},
rounded: {
borderRadius: 16,
},
})
- && 사용
// Box.js
<View styles={[styles.box, props.rounded && styles.rounded ]} />
const styles = StyleSheet.create({
box: {
width: 32,
height: 32,
backgroundColor: 'red',
},
rounded: {
borderRadius: 16,
},
})
2. 다양한 크기 구현하기
컴포넌트에 size라는 Props를 small, medium, large로 설정해 다양한 크기로 보여주자
// App.js
<Box size="large" />
// Box.js
<View styles={[sizes[props.size] ]} />
Box.defaultProps = {
size: 'medium',
}
const styles = StyleSheet.create({
small: {
width: 32,
height: 32,
},
medium: {
width: 64,
height: 64,
},
large: {
width: 128,
height: 128,
},
})
const sizes = {
small: styles.small,
medium: styles.medium,
large: styles.large,
}
3. 색상 변경하기
color의 값은 다양하므로 미리 선언하는 방식은 힘들고 그 대신 props로 받은 값을 스타일로 직접 넣어주면 쉽게 구현가능하다
// App.js
<Box color="blue" />
// Box.js
<View styles={[{ bacngroundColor: props.color }]} />
Box.defaultProps = {
color: 'black',
}
4. props 객체 구조 분해 할당
// App.js
<Box rounded size="medium" color="blue" />
// Box.js
const Box({ rounded, size, color }) => {
<View
style={[
styles.box,
rounded && stylels.rounded,
size[size],
{
backgroundColor: color,
},
]}
/>
}
Box.defaultProps = {
size: 'medium',
color: 'black',
}
const styles = styleSheet.create({
box: {
backgroundColor: 'black',
},
rounded: {
borderRadius: 16,
},
small: {
width: 32,
height: 32,
},
medium: {
width: 64,
height: 64,
},
large: {
width: 128,
height: 128,
},
})
const sizes = {
small: styles.small,
medium: styles.medium,
large: styles.large,
}
'REACT || REACT NATIVE' 카테고리의 다른 글
RN. android에서 글씨가 가려진다... (0) | 2022.10.01 |
---|---|
RN. 키보드에서 enter을 눌렀을 때, onPress 함수 호출 (0) | 2022.08.28 |
styled-componont에서 props 사용하기 (0) | 2022.08.06 |
React. useReducer (상태관리) (0) | 2022.08.02 |
REACT. JSX 문법 3/3 (0) | 2022.05.01 |
Comments