Reactjs
<ReactJs> SASS 버튼에 여러 옵션 주기 (@mixin, @include)
DevilFront
2020. 7. 27. 16:36
반응형
버튼의 크기와 색상을 입혀주는 작업을 해보장><
우선 classNames 라는 리액트 라이브러리를 깔아준 뒤에 문자열로 클래스명들을 받아 줄 수 있게 준비해주도록 한다. (굳이 classNames 를 이용해주지 않아도 된다!!)
classNames 라이브러리를 추가할 때는
yarn 을 쓸 때는 yarn add classnames
npm을 쓸 때는 npm install classnames 등으로 설치해준다.
설치가 되면 props 로 size 와 color 를 받아준다. 받아와준 props들이 그대로 <button> 태그의 클래스명으로 들어가게 되고 color와 size 의 기본값을 설정해준다. (defaultProps)
Button.scss 는 이런식으로 각각의 size 와 color 값에 해당하는 것들에 대한 스타일링을 준비해준다.
$blue : blue;
$gray : gray;
$pink : pink;
.Button{
display: inline-flex;
color: white;
font-weight: bold;
outline: none;
border:none;
cursor: pointer;
padding-left: 1rem;
padding-right: 1rem;
&.large{
height: 3.5rem;
font-size: 1.6rem;
}
&.medium{
height: 2.5rem;
font-size: 1rem;
}
&.small{
height: 1rem;
font-size: .7rem;
}
&.blue{
background-color: $blue;
&:hover{
background-color: lighten($blue ,20%);
}
&:active{
background-color: darken($blue, 20%);
}
}
&.gray{
background-color: $gray;
&:hover{
background-color: lighten($gray ,20%);
}
&:active{
background-color: darken($gray, 20%);
}
}
&.pink{
background-color: $pink;
&:hover{
background-color: lighten($pink ,20%);
}
&:active{
background-color: darken($pink, 20%);
}
}
}
이런식으로 각각의 버튼에 color 와 size 값을 전달해주게 되면
결과창에서 제대로 나오는 것을 확인 할수 있다. 하지만 Button.scss 코드에서
&.blue{
background-color: $blue;
&:hover{
background-color: lighten($blue ,20%);
}
&:active{
background-color: darken($blue, 20%);
}
}
&.gray{
background-color: $gray;
&:hover{
background-color: lighten($gray ,20%);
}
&:active{
background-color: darken($gray, 20%);
}
}
&.pink{
background-color: $pink;
&:hover{
background-color: lighten($pink ,20%);
}
&:active{
background-color: darken($pink, 20%);
}
}
이런식으로 구조가 비슷하고 반복되는 코드부분이 있는데 @mixin 과 @include 를 이용해서 코드를 훨씬 짧고 가독성 좋게 바꾸어 줄수 있다.
@mixin button-color($color){
background-color: $color;
&:hover{
background-color: lighten($color ,20%);
}
&:active{
background-color: darken($color, 20%);
}
}
&.blue{
@include button-color($blue);
}
&.gray{
@include button-color($gray);
}
&.pink{
@include button-color($pink);
}
이런식으로 @mixin 으로 반복되는 부분을 함수에 넣어주고 인자값을 받아주게 한 뒤에 각각의 클래스명일 때 @include 를 써주고 함수를 호출해주면 훨씬 간단한 코드가 완성되는 것을 볼 수가 있다.
반응형