import React from 'react';
import Counter from './Counter';
function App() {
return <Counter />
}
export default App;
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState<number>(0);
const onIncrease = () => setCount(count + 1);
const onDecrease = () => setCount(count - 1);
return (
<div>
<h1>{count}</h1>
<div>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
</div>
);
}
export default Counter;
useState
를 사용하실때 useState<number>()
와 같이 Generics
를 사용하여 해당 상태가 어떤 타입을 가지고 있을지 설정만 해주시면 됩니다.
useState
를 사용 할 때 Generics
를 사용하지 않아도 알아서 타입을 유추하기 때문에 생략해도 상관없습니다.
상태가 null일 수도 있고 아닐수도 있을때 Generics
을 useState
에 사용하면 좋습니다.
// 예 type Information = { name: string; description: string }; const [info, setInformation] = useState<Information | null>(null);
import React from 'react';
import MyForm from './component/MyForm';
function App() {
const onSubmit = (form: { name: string; description: string }) => {
console.log(form);
};
return (
<MyForm onSubmit={onSubmit}/>
)
}
export default App;
import React, { useState } from 'react';
type MyFormProps = {
onSubmit: (form: { name: string; description: string }) => void;
};
function MyForm({ onSubmit }: MyFormProps) {
const [form, setForm] = useState({
name: '',
description: ''
});
const { name, description } = form;
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setForm({
...form,
[name]: value
});
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
// 여기도 모르니까 any 로 하겠습니다.
e.preventDefault();
onSubmit(form);
setForm({
name: '',
description: ''
}); // 초기화
};
return (
<form onSubmit={handleSubmit}>
<input name="name" value={name} onChange={onChange} />
<input name="description" value={description} onChange={onChange} />
<button type="submit">등록</button>
</form>
);
}
export default MyForm;
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('Unhandled action');
}
}
function Counter() {
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;