티스토리 뷰

styled components 심화편

React의 styled components 심화 편이다.

설치와 기본적 사용은 이 글을 참고하자.

 

styled component

목차 ... styled-component에 대해 쓸려고 기본적 구글링을 하는데 혼란스러웠다... 뭔가.. 앞뒤가 맞지 않는 정보가 많았다... 그만큼 내 글이 더 도움이 된다는 뜻이지!! (무~~ 야~~~ 호~~~) 내일 포스트

sirong.tistory.com

 

//App.js
import React from "react";
import styled from 'styled-components';

function App() {
  return (
    <>
      <D_styled></D_styled>
      <D_styled></D_styled>
    </>
  );
}

const D_styled = styled.div`
  display: inline-block;
  width:100px;
  height:100px;
  margin: 10px;

  background: #e4fbff;
`;

export default App;

 

기본적인 스타일링 태그 2개를 만들었다.

여기서 배경색 코드를 좀 달리 해보자.

단일 스타일링

//App.js
import React from "react";
import styled from 'styled-components';

function App() {
  return (
    <>
      <D_styled></D_styled>
      <D_styled></D_styled>
    </>
  );
}

const D_styled = styled.div`
  display: inline-block;
  width:100px;
  height:100px;
  margin: 10px;

  background: ${(props) => props.bgPurple || "#e4fbff"};
  // porps.bgPurple 의 값이 없으면 background 값을 "#e4fbff"로 지정
`;

export default App;

배경색에 분기문 or(||)을 걸었고,

앞의 조건거짓이면 뒤의 값,

앞의 조건이 참이면 뒤의 값이 거짓이 된다.

D_styled 두 개 모두 props.bgPurple가 값을 가지지 않았기에 거짓,

뒤의 값 #e4fbff 이 참으로 실현되었다.

//App.js
import React from "react";
import styled from 'styled-components';

function App() {
  return (
    <>
      <D_styled></D_styled>
      <D_styled bgPurple="#7868e6"></D_styled>
    </>
  );
}

const D_styled = styled.div`
  display: inline-block;
  width:100px;
  height:100px;
  margin: 10px;

  background: ${(props) => props.bgPurple || "#e4fbff"};
`;

export default App;

이번에는 두 번째 태그에

bgPurple 값을 지정해주었다.

그러니 해당 태그의 배경색은 지정 값으로 반영되었다.

복수 스타일링

//App.js
import React from "react";
import styled, { css } from 'styled-components';

function App() {
  return (
    <>
      <D_styled></D_styled>
      <D_styled styleMore></D_styled>
    </>
  );
}

const D_styled = styled.div`
  display: inline-block;
  width:100px;
  height:100px;
  margin: 10px;
  background: #e4fbff;

  ${(props) =>
    props.styleMore && css`
      width:300px;
      height:300px;
      background: #7868e6;
      border-radius: 20px;
      box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
  `}
`;

export default App;

으음.. 뭐 익숙하지 않을 뿐

보면 그렇게 어렵지는 않다.

styleMore이 참이면 &&(and) 뒤에껄 실행시킨다는 뜻이다.

'웹개발(프론트) > React' 카테고리의 다른 글

React cookie  (0) 2021.04.20
createElement 스타일 변경  (0) 2021.04.18
Redux Toolkit  (0) 2021.04.15
Redux by react  (0) 2021.04.14
Redux  (0) 2021.04.12
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/11   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함