티스토리 뷰
1. useState를 사용하기 위해 먼저 해당 Hook을 임포트 해야 합니다.
import { useState } from 'react';
2. useState를 사용하여 상태를 선언합니다.
상태를 선언할 때, 초기값을 인자로 전달합니다. 'useState' 는 배열을 반환하며, 첫번째 요소는 상태값(state value),
두번째 요소는 상태를 갱신 할 수 있는 함수(state updater function)입니다.
const [state, setState] = useState(initialState);
3. useState 코드 예시
import { useState } from 'react';
function App() {
const [amount, setAmount] = useState(0);
const [flipped, setFlipped] = useState(false);
function onChange(e) {
setAmount(e.target.value);
}
function reset() {
setAmount(0);
}
function onFlip() {
reset();
setFlipped((current) => !current);
}
return (
<div className="App">
<h1>Super Converter</h1>
<label for="minutes">Minutes</label>
<input
value={flipped ? amount * 60 : amount}
id="minutes"
placeholder="Minutes"
type="number"
onChange={onChange}
disabled={flipped}
/>
<div>
<label for="hours">Hours</label>
<input
value={flipped ? amount : parseInt(amount / 60)}
id="hours"
placeholder="Hours"
type="number"
disabled={!flipped}
onChange={onChange}
/>
</div>
<button onClick={reset}>RESET</button>
<button onClick={onFlip}>FLIP</button>
{/* <Test /> */}
</div>
);
}
export default App;
위 코드를 통해 분단위를 시간단위로 그리고 flip버튼 클릭시 시간 단위를 분단위로 바꿔주는 코드를 완성했습니다.
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- localStorage
- Hook
- setitem
- createElement
- 데드락
- react
- Let
- useState
- padStart
- Geolocation
- const
- 스코프
- var
- classList
- setTimeout
- getitem
- Return
- Navigator
- setinterval
- console.log
- new Date()
- 얕은복사
- 호이스팅
- 교착상태
- getCurrentPosition
- 브라우저 저장소
- removeitem
- e.preventDefault()
- 깊은복사
- innerText
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
29 | 30 |
글 보관함