react.js

[react 리액트] CSS 작성법

코복이 2023. 5. 26. 16:17
728x90

 

1. 태그에 직접 Style 넣기

* 보통 이렇게 inline으로 작업하진 않지만 참고

 

 

1) 주의할 점은, 스타일을 객체로 넣어야 한다는 것!

<p style={{color="red", fontWeight="30pt"}}>이렇게 객체로 작성</p>

2) 값은 ""따옴표로 감싸준다. (only 숫자는 그냥 기입해도 무방)

3) html + css 에서는 font-weight 인데 리액트에서는 fontWeight (다 이런식)

const Hellow = (prop) => {
    return <div>
        <p
            style={{
                color: 'red',
                fontWeight: 500
            }}>Hellow</p>
        <p
            style={{
                color: 'green',
                fontWeight: 900
            }}>{prop.name}</p>
        <h2>you are {prop.age} years old</h2>
        <Wolrd/>
    </div>
}

 

 

 

2. css 파일 활용하기

* css 파일은 두 가지 종류가 있는데 전역에 영향을 미치는 css와 컴포넌트 전용 css가 있다

* class 선택자 사용하는 경우 className="" 으로 해야 함.

 

 

1) 전역 css 파일

- html + css 와 동일한 사용성

- Something.css 파일과 Nothing.css 파일이 있고 두개에 모두 .box{color: 썸띵엔 블랙, 낫띵엔 레드}가 있으면 오버라이딩 되어 하나만 따름. (둘 다 전역에 영향을 미치기 때문)

css 파일에 스타일 정의해주고 태그에 붙이면 됨

import '../nice.css';

const Hellow = (prop) => {
    return <div>
        <p className="nice">you are {prop.age} years old</p>
        <p className="nice">Helow</p>
    </div>
}

 

 

 

2) 컴포넌트 전용 css 파일

- 모듈화하여 전역 스타일과 중복을 피할 수 있음.

- import한 컴포넌트에서만 우선적으로 쓰이는 스타일

파일명이름.module.css (module이 들어가야 함)

import 할 때 import styles form "경로.css"  (styles가 들어가야 함)

스타일 적용할 때 클래스 이름을 "이름" 이 아닌 className={styles.이름}으로 해야 함

모듈화하였다.

import styles from "./Hellow.module.css"

const Hellow = (prop) => {
    return <div>
        <p className={styles.box}>Hellow</p>
    </div>
}

 

728x90