리액트 3주차 정리

리액트 스타일링에 관하여

개요

리액트의 고질적인 문제 : css가 스코핑되지 않고 전체 컴포넌트에 다 먹힌다.

  • [해결법 1] 사람이 관리 : 초기에는, 네이밍 규칙을 정해 사람들이 직접 관리했다.
  • [해결법 2] 스타일드 컴포넌트 : 사람이 하니 힘들다. 자동으로 가자. 해서 나온 자동의 극단
  • [해결법 3] css 모듈, sass 모듈 : 그 양 극단의 중간

1. Style Loaders

cra를 통해 app을 만들고, npm run eject 해본다.
webpack.config.js 파일에 설정이 있다.
css sass 파일을 만들고, import 해서 사용하면 된다. (네이밍 규칙 사용)

2. css module, sass module

이전에 .css 파일을 만들어 사용했다면, 이번엔 .module.css를 만들어 import하여 사용한다. styles["클래스명"] <- 이렇게 사용하면 된다.

- 사용 예 1

import React from "react";
import logo from "./logo.svg";
import styles from "./App.module.css"; // import

function App() {
  console.log(styles);
  return (
    <div className={styles["App"]}>
      <header className={styles["App-header"]}>
        <img src={logo} className={styles["App-logo"]} alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className={styles["App-link"]}
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

위 코드에 import된 css 파일은 다음과 같다

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #09d3ac;
}
  • 사용 예2 : components

Button.module.css

.button {
  background: transparent;
  border-radius: 3px;
  border: 2px solid palevioletred;
  color: palevioletred;
  margin: 0 1em;
  padding: 0.25em 1em;
  font-size: 20px;
}

Button.jsx

import React from "react";
import styles from "./Button.module.css";

export default function Button(props) {
  return <button className={styles.button} {...props} />;
}

3. Styled Components

설치

npm i styled-components

사용 예 1

styled.<태그>\`스타일\`

import styled from "styled-components";

const StyledButton = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid palevioletred;
  color: palevioletred;
  margin: 0 1em;
  padding: 0.25em 1em;
`;

export default StyledButton;

위에 사용된 템플릿은 원래 있는 문법이다.

import React from "react";
import StyledButton from "./components/StyledButton";

function App() {
  return (
    <div className="App">
      <p>
        <StyledButton>버튼</StyledButton>
      </p>
    </div>
  );
}

export default App;

사용 예 2

${props => css스타일}

import styled, { css } from "styled-components";

const StyledButton = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid palevioletred;
  color: palevioletred;
  margin: 0 1em;
  padding: 0.25em 1em;

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

export default StyledButton;
import React from "react";
import StyledButton from "./components/StyledButton";

function App() {
  return (
    <div className="App">
      <p>
        <StyledButton>버튼</StyledButton>
        <StyledButton primary>Primary 버튼</StyledButton>
      </p>
    </div>
  );
}

export default App;

ref

마우스가 엔터되었을 때, input에 스타일을 준다고 할 때, ref를 사용하여 구현할 수 있다.

import styled from "styled-components";

const StyledInput = styled.input`
  padding: 0.5em;
  margin: 0.5em;
  color: palevioletred;
  background: papayawhip;
  border: none;
  border-radius: 3px;
`;

export default StyledInput;
import React from "react";
import StyledInput from "./components/StyledInput";

class App extends React.Component {
  inputRef = React.createRef();
  render() {
    return (
      <div className="App">
        <p>
          <StyledInput
            ref={this.inputRef}
            placeholder="Hover to focus!"
            onMouseEnter={() => {
              this.inputRef.current.focus();
            }}
          />
        </p>
      </div>
    );
  }
}

export default App;

카테고리:

업데이트: