본문 바로가기
React를 같이 배워보자

React9일차-Component style

by 멈추지않아 2022. 1. 28.

오늘은 컴포넌트 한개에만 스타일을 넣는것을 해보겠다.

오늘은 저번게시물에서 만든 폴더에서 vscode를 열고 npm start 해보자

src/component StyledButton.jsx 만들기 안에

import styled from "styled-components";
const StyleButton = styled.button`
  background: transparent;
  border-radious: 4px;
  border: 2px solid palevioletred;
  color: palevioletred;
  margin: 0.1em;
  padding: 0.25em 1em;
  font-size: 20px;
  ${(props) =>
    props.primary &&
    `
      background: palevioletred;
      color: white;
    `}
`;
export default StyleButton;

작성

우선  이거부터 설명해보면 

const StyleButton = styled.button``,

 ${(props) =>
    props.primary &&
    `
      background: palevioletred;
      color: white;
    `}

이 두부분 말고는 다 봤던거라서 이해가 될것이다

우선 기본형식은 변수명=styled.만들요소`스타일내용` 이다.

지금으 button이라는 요소를 만들어서 아래 스타일을 적용하겠다. 라는 의미이다

export default StyleButton;

StyleButton이라는 것을 내보내 겠다는 의미이다.

 ${(props) =>
    props.primary &&
    `
      background: palevioletred;
      color: white;
    `}

이거는 props 즉 전달받은 요소중에 primary라는 게있으면 아래 css를 적용하겠다는 의미이다.

그다음 App.js가서

import StyledButton from "./componenet/StyledButton";

import모여있는데 추가해주고

return 내부를

(
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          <StyledButton>버튼</StyledButton>
        </p>
      </header>
    </div>
  )

이렇게 변경

이러고 화면을 npm start화면을 보면

이렇게 정의한 css가 반영된 버튼이 만들어져있다.

여기서는 전달하는 요소에 primary가 없어서 배경화면이 뒷배경과 색깔이 같다

그러면

<StyledButton>버튼</StyledButton>
밑에
<StyledButton primary >버튼</StyledButton>
를 추가해보자

이렇게 배경화면이 다른 버튼이 생겼다. 우리는 이렇게 특정 컴포넌트만의 css를 적용시켜줄수있다.

App.js의 function 위에 

const PrimaryStyleButton = styled(StyledButton)`
  background: palevioletred;
  color: white;
`;
추가하고  import 모여있는곳에 
import styled, { createGlobalStyle } from "styled-components";
를 추가하자
<StyledButton primary >버튼</StyledButton> 밑에
<PrimaryStyleButton>버튼</PrimaryStyleButton>추가

그러면 똑같은 버튼이 한개 더생겼을거다

분명 이름이 다른데 어떻게 생겼을까 의문이 생길수도 있다.

const PrimaryStyleButton = styled(StyledButton)``

이부분을 해석해 보면 PrimatyStyleButton이라는 변수에 StyledButton의 style을 다  넣고`` 사이에 잇는 요소를 추가하는 것이다.

즉, StyledButton+''사이에있는 css요소 그러므로 그림처럼 똑같은 버튼이 생기는것이다.

이렇게 비슷한것은 새로 만들지 않고 여기서 간단한 코드로 만들수도 있다.

<StyleㅇButton as="a" href="/">
            버튼
          </StyledButton>
 
이거를 다른 버튼 밑에 넣어보자

분명 버튼인데 a태그처럼 링크를 해준다 이건 as이부분때문에 가능하다 특정요소를 as다음에있는 태그처럼 바꿔준다.

이렇게 button태그를 a태그로 디자인변경없이 만들어줄수 있다.

button모여있는곳에 

<StyledButton as={UpperCaseButton}>button</StyledButton>
추가
function 위에
const UpperCaseButton = (props) => (
  <button className={props.className} children={props.children.toUpperCase()} />
);
추가

분명 코드는 소문자인데 대문자로 나타난다. 왜 이렇게 되는지 한번 알아보겠다.

<button className={props.className} children={props.children.toUpperCase()} />

이걸 화인해보면 className은 기본적으로 컴포넌트를 만들면 특정규칙에의해 부여된다. 그것이 props에 저장되고

props.className으로 저렇게 저장할수 있다. 그리고 children저건 자식 즉 내부에있는 button이 다.

이것을 props.childern으로 받아서 toUpperCase로 대문자로 만들어주었다.

그래서 결국 StyledButton을 UpperCaseButton처럼 만들어주는데 그것의 클래스이름은 지금 만든  StyledButton이랑 같고

children은 적혀있는 button을 다 대문자로 만들어주겠다는 의미이다. 

즉 <StyledButton>BUTTON</StyledButton>이거랑 똑같은 말이된다.(클래스이름은 생략이 된다.)

function 위에 

const MyButton = (props) => (
  <button className={props.className} children={`MyButton ${props.children}`} />
);
const StyleMyButton = styled(MyButton)`
  background: transparent;
  border-radious: 4px;
  border: 2px solid ${(props) => props.color || "palevioletred"};
  color: palevioletred;
  margin: 0.1em;
  padding: 0.25em 1em;
  font-size: 20px;
  ${(props) =>
    props.primary &&
    `
      background: palevioletred;
      color: white;
    `}
  :hover {
    border: 2px solid red;
  }
`;
추가
버튼 모여있는데
<StyleMyButton color="green">button</StyleMyButton>
추가

자 여기서는 특징이 글자가 달라진거랑 테두리 이다

우선 테두리부터 알아보겠다.

 border: 2px solid ${(props) => props.color || "palevioletred"};

이부분을 해석하면 props로 전달받은 데이터에서 color라는 이름이  있으면 그 color값을 적용하고 아니면 palevioletred를 적용한다는 의미이다. ||=or이기 때문에 한개라도 참이면 그자리에서 연산을 멈춘다. 즉 props.color라는게 존재하면 뒤에꺼를 실행하지 않는것이다. 그래서 테두리가 green이다 

<StyleMyButton color="green">button</StyleMyButton>여기서 color=green이 전달  되었다.

그럼이제 글자부분을 보겠다. 왜 MyButton이 추가 되었나 하면children={`MyButton ${props.children}`} 이부분이다. 즉 StyleMyButton 은 MyButton 을 실행하고 만들어진다. MyButton에서 return 안에 있는 자식 요소인 button을 MyButton 자식요소 이렇게 바꾸겠다고 선언한것이다.

StyleMyButton을 만들때는 우선 MyButton을 만들고 그걸 가져와서 스타일을 추가하게된다. 그러므로 글자와 테두리 둘다 변한다.

function 위에 const GlobalStyle = createGlobalStyle`button{
  color:yellow
}`;
추가return 최상위 요소 바로 밑에<GlobalStyle />그리고 버튼 모여있는데 <button>jk</button>추가

이렇게 보면 안에 버튼이 만들어졌느데 안에 글시가 노란색이다. 이건 왜 스타일을 변한건지 알아보자 분명 특별한 이름이 아닌 그냥 button이다

createGlobalStyle`button이거는 전체적인 스타일을 명세하는거다 

즉 만들어놓은 변수 컴포넌트 밑에잇는건 기본적으로 여기 적혀있는 스타일이 적용된다.

그래서 해석해보면 최상위요소 말고는 싹다 버튼 글자색을 노란색이라는 말이다. 그래서 이미지처럼 노란색 글자가 나온다.

어 그런데 왜 다른건 다 색깔이 안변했나요 할수 있다.  하지만 이건 젤 먼저 적용된다고 생각하면 편하다. 먼전 노란색으로 다 적용이 되고 그이후에 각 컴포넌트별로 색깔을 설정값을 넣었다면 그색깔로 변한다. 하지만 색깔 설정값이 없다면 노란색으로 나올것이다.

src/componenet/StyleA.jsx 만들어서
import styled from "styled-components";
const StyleA = styled.a.attrs((props) => ({
  href: "https://www.google.co.kr/",
  target: "_BLANK",
}))`
  color: ${(props) => [props.color]};
`;

추가

import 모인곳에 

import StyleA from "./componenet/StyleA";
버튼 모인곳에  

<StyleA>link</StyleA>

이렇게 생기는데 a태그처럼 생긴다 그리고 클릭하면 구글에 연결되고 새창으로 열린다.

딱히 href target은 없는데 어떻게 연결되는것일까 의문일수 있다.

styled.a.attrs((props) => ({
  href: "https://www.google.co.kr/",
  target: "_BLANK",
}))`

여기를 보면알수있다. 이거는 기본값을 설정해주는거다.

즉 a태그로 만들고 그 속성에   href: "https://www.google.co.kr/",
  target: "_BLANK",이거 두개를 추가한것이다.

style.태그이름.attrs((저장할변수)=>({설정할 기본값})이렇게 되서 target  href가 기본값으로 연결되어 있는것이다.그런데 왜 새창으로 열리는지 모를수도 있다. target: "_BLANK" 이것이 새창으로 열리라는 의미이다.

이번게시물은 길고 어렵지만 이해해보면 재밌고 잘가지고 놀수있다. ㅎㅎ 가지고 장난쳐보면 이해가 쉬울것이다.

'React를 같이 배워보자' 카테고리의 다른 글

React10일차-antdesign  (0) 2022.01.29
React10일차-reactshadow  (0) 2022.01.29
React9일차-Css,SCSS  (0) 2022.01.28
React8일차-Login  (0) 2022.01.27
React7일차-Link와 NavLink  (0) 2022.01.26