TS-REACT-TUTORIAL
Counter_Reduce.tsx
2022.07.26 - [Coding/TypeScript] - [TS / React] React에서 TS 사용해보기
[TS / React] React에서 TS 사용해보기
npx create-react-app ts-react-tutorial --template typescript 뒤에 --template typescript 붙이면 typescript가 포함된 리액트 폴더를 만들 수 있음 TS-REACT-TUTORIAL Counter.tsx import React, { useState..
7ingout.tistory.com
여기 Timer를 Reducer로 구현해보자 !
import React, { useReducer } from 'react';
// 액션타입과 리듀서함수 생성
// 액션을 | 로 연달아서 쭉 나열함
type Action = { type: 'INCREASE' } | { type: 'DECREASE' }
function reducer(state: number, action:Action): number {
switch(action.type) {
case 'INCREASE':
return state+1;
case 'DECREASE':
return state-1;
default:
throw new Error('없는 액션 타입입니다.')
}
}
const Counter_Reduce = () => {
const [count, dispatch] = useReducer(reducer, 0)
const onIncrease = () => dispatch({ type: 'INCREASE' })
const onDecrease = () => dispatch({ type: 'DECREASE' })
return (
<div>
<h1>{count}</h1>
<div>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
</div>
);
};
export default Counter_Reduce;
ReducerSample.tsx
import React, { useReducer } from 'react';
type Color = 'red' | 'orange' | 'green'
type State = {
count: number;
text: string;
color: Color;
isGood: boolean
}
type Action = {type: 'SET_COUNT'; count: number}
| {type: 'SET_TEXT'; text: string}
| {type: 'SET_COLOR'; color: Color}
| {type: 'TOGGLE_GOOD'}
function reducer(state: State, action: Action) : State {
switch(action.type) {
case 'SET_COUNT':
return {
...state,
count: action.count
}
case 'SET_TEXT':
return {
...state,
text: action.text
}
case 'SET_COLOR':
return {
...state,
color: action.color
}
case 'TOGGLE_GOOD':
return {
...state,
isGood: !state.isGood
}
default:
throw new Error('액션이 없어요')
}
}
const ReducerSample = () => {
const [state, dispatch] = useReducer(reducer, {
count: 0,
text: 'Hello',
color: 'red',
isGood: true
});
const setCount = () => dispatch({ type: 'SET_COUNT', count:5 })
const setText = () => dispatch({ type:'SET_TEXT', text: 'bye' })
const setColor = () => dispatch({ type: 'SET_COLOR', color: 'orange' })
const toggleGood = () => dispatch({ type:'TOGGLE_GOOD' })
return (
<div>
<p>
<code>count : </code> {state.count}
</p>
<p>
<code>text : </code> {state.text}
</p>
<p>
<code>color : </code> {state.color}
</p>
<p>
<code>isGood : </code> {state.isGood? 'true' : 'false'}
</p>
<div>
<button onClick={setCount}>setcount</button>
<button onClick={setText}>setText</button>
<button onClick={setColor}>setcolor</button>
<button onClick={toggleGood}>toggleGood</button>
</div>
</div>
);
};
export default ReducerSample;
'Stack > TypeScript' 카테고리의 다른 글
[TS / React] To-Do List 구현 (0) | 2022.07.27 |
---|---|
[TS / React] props 전달 (0) | 2022.07.27 |
[TS / React] React에서 TS 사용해보기 (0) | 2022.07.26 |
[TS] Generic (0) | 2022.07.26 |
[TS] Interface 함수 (0) | 2022.07.26 |