Notice
Recent Posts
Recent Comments
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 스쿠버다이빙
- 막탄
- 네이버페이사기
- 중고거래사기
- Hooks
- 해외여행
- 구분
- autocomplate
- Webpack
- js
- 정규식
- 세부
- 마사지
- 맛사지
- 유효성검사
- 사기
- webpack.config.js
- 특수문자
- 중고나라
- plugin
- 삼성무선청소기제트
- 정직하게사세요
- 자동완성
- 스노쿨링
- 여행
- 중고나라사기
- ES6
- REACT
- JavaScript
Archives
- Today
- Total
Ryu.log
[ React + redux 03 ] 애플리케이션 상태관리 - Counter 컴포넌트 생성 본문
01. Counter 컴포넌트 생성
첫 프리젠테이셔널 컴포넌트인 카운터 컴포넌트를 만들어보자. 이 컴포넌트는 숫자와 색상 값,
더하기, 빼기, 색상 변경 함수를 props로 받는다.
// src/components/Counter.js
import React from 'react';
import PropType from 'prop-types';
import './Counter.css';
const Counter = ({ number, color, onIncrement, onDecrement, onSetColor }) => {
return (
<div
className="Counter"
onClick={onIncrement}
onContexMenu={(e) => {
e.preventDefault();
onDecrement();
}}
onDoubleClick={onSetColor}
style={{
backgroundColor: color
}}>
{number}
</div>
);
};
Counter.propTypes = {
number: PropType.number,
color: PropType.string,
onIncrement: PropType.func,
onDecrement: PropType.func,
onSetColor: PropType.func
};
Counter.defaultProps = {
number: 0,
color: 'black',
onIncrement: () => console.warn('onIncrement not defined'),
onDecrement: () => console.warn('onDecrement not defined'),
onSetColor: () => console.warn('onSetColor not defined')
};
export default Counter;이 코드에서 onContextMenu는 마우스 오른쪽 버튼을 눌렀을 때 메뉴가 열리는 이벤트를 의미한다.
이 함수가 실행될 때 e.preventDefault() 함수를 호출하면 메뉴가 열리는것을 방지할 수 있다.
컴포넌트 코드의 아랫쪽에는 props 기본 값을 설정해 주었다. 카운터의 기본숫자는 0, 색상은 검은색,
함수가 전달되지 않았을 때는 경고 메시지를 출력하도록 설정했다.
이번에는 스타일을 적용해보자.
// src/components/Counter.css
.Counter {
/* 레이아웃 */
width: 10rem;
height: 10rem;
display: flex;
align-items: center;
justify-content: center;
margin: 1rem;
/* 색상 */
color: white;
/* 폰트 */
font-size: 3rem;
/* 기타 */
border-radius: 100%;
cursor: pointer;
user-select: none;
transition: background-color 0.75s;
}
컴포넌트 모양은 동그라미, 숫자는 흰색상으로 동그라미의 가운데에 위치하도록 설정했다.
이 컴포넌트가 어떻게 보이는지 확인해보자.
App.js 파일에서 임시로 불러와서 렌더링한 뒤에 마우스 왼쪽클릭, 오른쪽클릭, 더블클릭을 해서
각 이벤트에 지정한 기본함수가 제대로 실행되는지 확인해보자.
// src/containers/App.js
import React, { Component } from 'react';
import Counter from '../components/Counter'
class App extends Component {
render() {
return (
<div>
<Counter/>
</div>
);
}
}
export default App;
'Prev-content' 카테고리의 다른 글
| [ React + redux 04 ] 애플리케이션 상태관리 - 리듀서 생성 (0) | 2018.09.20 |
|---|---|
| [ React + redux 03 ] 애플리케이션 상태관리 - 액션생성 (0) | 2018.09.19 |
| [ React + redux 02 ] 애플리케이션 상태관리 - 기본적인 틀 생성 (0) | 2018.09.13 |
| [ React + redux 01 ] 애플리케이션 상태관리 - 작업환경 설정 (0) | 2018.09.12 |
| [ React redux 05 ] 리덕스의 세가지 규칙 및 정리 (0) | 2018.09.07 |
Comments