본문 바로가기

React

[React] CSS 클래스 네임

index.css 파일을 새로 생성한 후, 다음과 같이 스타일 적용

 

 

이후, index.js 에서 다음처럼 파일을 import 해줌.

 

 

페이지에 글자색과 배경색이 잘 저장된 모습을 확인할 수 있다.

 

 

Elements > head > style 코드가 잘 적용되어 있음.

자바스크립트에 CSS 파일을 import 하게되면, <head> 태그 안에 style 태그가 자동으로 작성되기 때문 

 


Button.css 파일을 만들어 다음처럼 작성한 후,

.Button {
    padding: 14px 27px;
    border-radius: 9999px;
    outline: none;
    cursor: pointer;
    font-size: 17px;
}

.Button.blue {
    background-color: rgba(0, 89, 255, 0.2);
    border: solid 1px #7090ff;
    color: #7090ff;
}

.Button.red {
    background-color: rgba(255, 78, 78, 0.2);
    border: solid 1px #ff4664;
    color: #ff4664;
}

 

Button.js 에 css 파일을 import 하고 다음처럼 적용하면, 

import './Button.css'

function Button({ children, onClick, color = 'blue' }) { // Button 태그 안, text prop 을 보여주는 함수
    const classNames = `Button ${color}`
    return <button className={classNames} onClick={onClick}>{children}</button>
}

export default Button;

 

전과 똑같은 스타일 속성이 잘 적용되었음.

 


CSS에는 여백을 주는 margin 과 같은 요소 내부보다는 외부와 관련한 속성들이 있는데, 이런 속성은 component 내부보다는 외부에서 정리하는것이 좋음.

 

App.css 에 다음과 같은 속성을 저장한 후

.App .App-button {
    margin: 6px;
}

 

App.js 에 위 파일을 import 한 후 실행하면,

import Board from "./Board";
import Button from "./Button";
import { useState } from 'react';
import './App.css';


function random(n) {
    return Math.ceil(Math.random() * n);
}

function App() {
    const [myHistory, setMyHistory] = useState([]);
    const [otherHistory, setOtherHistory] = useState([]);

    const handleRollClick = () => {
        const nextMyNum = random(6);
        const nextOtherNum = random(6);
        setMyHistory([...myHistory, nextMyNum]);
        setOtherHistory([...otherHistory, nextOtherNum]);
    };

    const handleClearClick = () => {
        setMyHistory([]);
        setOtherHistory([]);
    };


    return (
        <div className = "App">
            <div>
                <Button className="App-button" color="blue" onClick={handleRollClick}>던지기</Button>
                <Button className="App-button" color="red" onClick={handleClearClick}>처음부터</Button>
            </div>
            <div>
                <Board className="App-button" name ="나" color="blue" gameHistory={myHistory}></Board>
                <Board className="App-button" name ="상대" color="red" gameHistory={otherHistory}></Board>
            </div>
        </div>
    );
}

export default App;

여백이 잘 적용된 것을 확인할 수 있다.

 

이 방법은 직관적으로 코드를 다룰 수 있게 됨.

'React' 카테고리의 다른 글

[React] BABEL  (0) 2023.03.24
[React] 리액트 명령어 정리  (0) 2023.03.24
[React] 인라인 스타일  (0) 2023.03.23
[React] 참조형 State/ 주사위 총점 계산 및 기록하기  (0) 2023.03.18
[React] State/ 주사위 던지기  (0) 2023.03.18