[React] React Sass(유용한 CSS전처리기)
시간이 애매해 실습 전 내용정리 먼저!
1. 설치
npm install sass --save
node-modules폴더 하위에 sass폴더 생성
--save옵션으로 package.json 업데이트
// package.json
{
"name": "westagram-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"node-sass": "^4.14.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
}
}
2. 확장자 변경
확장자 .css => .scss변경
.js파일 내 import구문도 수정
3. Nesting 기능
JSX 최상위요소 className과 컴포넌트 이름을 일치시켜준 후(ex. login Login), .scss파일에서 최상위요소 안쪽에서 하위요소 스타일 속성 정의(.login에 네스팅해서 작성). React에서 Router사용시 index에 코드가 모이면서 css가 여러 컴포넌트에 적용되는 것 방지할 수 있음.
// css
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
// Sass
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
li {
display: inline-block;
}
}
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
4. 변수 활용, & 연산자, mixin 등 기본 기능
$ : 변수기능
@mixin - @include : 코드묶음
& : 부모선택자
// css
login-container {
display: flex;
justify-content: center;
align-items: center
}
button {
width: 200px;
height: 100px;
background-color: blue;
}
button:hover {
background-color: red;
cursor: pointer;
}
input {
background-color: blue;
}
input:focus {
background-color: red;
}
// Sass
$theme-color: blue;
$border-style: 1px black solid;
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center
}
login-container {
@include flex-center;
button {
width: 200px;
height: 100px;
background-color: $theme-color;
&:hover {
background-color: red;
cursor: pointer;
}
}
input {
background-color: $theme-color;
&:focus {
background-color: red;
}
}
}
5. import
import 사용 시 CSS와 문법의 차이가 있음. 괄호대신 "" 또는 '' 사용. 폰트 사용 시에는 일반 CSS와 동일한 import를 사용해도 되는 것 같음.
// SCSS
@import "inc.css";
// CSS
@import url(inc.css);
6. use
5번과 같이 import를 사용할 수도 있으나 use기능을 사용하는 것이 코드중복 예방에 좋음.
// _color.scss
$bg-login: #fafafa;
@mixin flex($justify: flex-start, $align: center) {
display: flex;
justify-content: $justify;
align-items: $align;
}
// use를 통해 불러오기
@use '../../../styles/color.scss' as clr;
// 사용하기
#wrap {
background: clr.$bg-login;
}
#header {
@include mixin.flex($align: center);
}
Author And Source
이 문제에 관하여([React] React Sass(유용한 CSS전처리기)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@hyeonze/React-React-Sass-프리뷰저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)