[ReactNative] styled-components

Mary·2024년 5월 2일

ReactNative

목록 보기
4/14

styled-components란

JavaScript 파일 안에 스타일 코드를 작성할 수 있는 라이브러리

간단하게 스타일이 적용된 컴퍼넌트를 만드는 라이브러리라고 생각하면 됨

스타일 적용

Tagged Template Literals

import styled from 'styled-components/native';

const 컴포넌트이름 = styled.컴포넌트`, 스타일코드

주의
styled는 styled component에서 가져오는 것이 아니라 styled-component의 native에서 가져와야함

styled뒤에 작성하는 component는 반드시 react-native에서 제공하는 component를 사용해야함

스타일 재사용

const 컴포넌트이름 = styled(컴포넌트)`, 스타일코드

밑에 처럼 아예 style코드만 따로 만들어서 재사용해도 됨

import {css} from 'styled-components/native';

const 스타일이름 = css`, 스타일코드
const 컴포넌트이름 = styled.컴포넌트` ${스타일이름}, 스타일 코드

props

원래 style sheet에서는 props에 접근 못함
하지만 styled-component사용하면 component에 props 전달 하고 스타일을 설정하는 곳에서 prop를 이용해서 처리 가능

const StyledText = styled.Text`
	font-size: 20px;
	font-weight: 600;
	color: ${props => (props.name === 'Mary' ? 'black' : 'red')};
`;

export default function App() {

	const name = 'Mary';
  	return (
    	<View style={styles.container}>
      		<StyledText name={name}>{name}</StyledText>
    
  		</View>
    
    );

}


삼항연산자

condition ? exprIfTrue : exprIffalse;

attr

component의 속성들은 component를 사용하는 곳에서 설정하는 것이 일반적.

하지만 styled-component를 사용하면 스타일을 정의하는 곳에서 compoent의 속성도 설정 가능

styled.컴포넌트.attr({속성 설정})'스타일코드'```



```javascript
styled.컴포넌트.attrs(props => {
return {속성 설정};})'스타일코드'

📍 props를 전달받아 그 값에 따라 속성 설정 변경 가능

ThemeProvider

미리 정의된 값들을 지정해서 해당 값을 사용할 수 있도록 해줌

const styledText = styled.Text`
	font-size: 20px;
	color: ${props => props.theme.txtColor};
	background-color: ${({ theme }) => theme.bgColor};
`;

export default function App() {

  const theme = { txtColor: 'green', bgcolor: 'gray'};
  return (
    <ThemeProvider theme={theme}>
  		<View style={styles.container}>
          <StyledText>Hello</StyledText>
  		</View>
  </ThemeProvider>
  
  
  );
}

0개의 댓글