728x90
참고자료: 노마드 코더 ReactJS로 영화 웹 서비스 만들기 https://nomadcoders.co/react-for-beginners/lobby
1. 분단위 시단위 둘 다 convert하는 기능 만들기
<script type="text/babel">
function App() {
const [amount, setAmount] = React.useState(0);
const [flipped, setFlipped] = React.useState(false);
const onChange = (event) => {
setAmount(event.target.value);
}
const reset = () => setAmount(0);
const onFlip = () => {
reset();
setFlipped((current) => !current);
};
return(
<div>
<h1 className="hi">Super Converter</h1>
<div>
<label htmlFor="minutes">Minutes</label>
<input
value={flipped ? amount * 60 : amount}
id="minutes"
placeholder="Minutes"
type="number"
onChange={onChange}
disabled={flipped}
/>
</div>
<div>
<label htmlFor="hours">Hours</label>
<input
value={flipped ? amount : Math.round(amount / 60)}
id="hours"
placeholder="Hours"
type="number"
disabled={!flipped}
/>
</div>
<button onClick={reset}>Reset</button>
<button onClick={onFlip}>Flip</button>
</div>
);
}
const root = document.getElementById("root");
ReactDOM.render(<App />, root);
</script>
👉🏻전체 코드
filp 버튼 만들기
<button onClick={onFlip}>Flip</button>
👉🏻reset 버튼 아래에 flip 버튼을 만들어준다.
const [flipped, setFlipped] = React.useState(false);
👉🏻useState를 통해 boolean으로 flipped state와 setFlipped를 만들어준다.
const onFlip = () => {
reset();
setFlipped((current) => !current);
};
👉🏻onFlip 함수를 만들어준다.
- reset 함수를 실행하고 flipped가 true면 false로 false면 true로 바꿔준다.
input 상태 변화시키기
const [amount, setAmount] = React.useState(0);
👉🏻먼저 minutes state를 amount로 명칭을 바꾼다.
<div>
<label htmlFor="minutes">Minutes</label>
<input
value={flipped ? amount * 60 : amount}
id="minutes"
placeholder="Minutes"
type="number"
onChange={onChange}
disabled={flipped}
/>
</div>
<div>
<label htmlFor="hours">Hours</label>
<input
value={flipped ? amount : Math.round(amount / 60)}
id="hours"
placeholder="Hours"
type="number"
disabled={!flipped}
/>
</div>
- 각 input에 disabled 속성을 추가한다.
- minutes input은 flipped가 false일 때 나타난다.
- hours input은 flipped가 true일 때 나타난다.
- 각 input의 value도 flipped 값에 따라 설정한다.
- minutes input은 flipped가 true일때 amount(이 때는 hours input에서 입력한 값)에 60을 곱한 값을 return하고 false일 때는 사용자가 입력하는 값을 return한다.
- hours input은 flipped가 false일때 amount(이 때는 minutes input에서 입력한 값)에 60을 나눈 값을 return하고 true일 때는 사용자가 입력하는 값을 return한다.
728x90
'그 땐 Front했지 > 그 땐 React했지' 카테고리의 다른 글
[노마드/React로 영화 웹 서비스 만들기] Ch04 PROPS | 0. Props (0) | 2022.05.24 |
---|---|
[노마드/React로 영화 웹 서비스 만들기] Ch03 STATE | 9. Final Practice and Recap (0) | 2022.05.23 |
[노마드/React로 영화 웹 서비스 만들기] Ch03 STATE | 6. State Practice part One (0) | 2022.05.23 |
[노마드/React로 영화 웹 서비스 만들기] Ch03 STATE | 5. Inputs and State (0) | 2022.05.17 |
[노마드/React로 영화 웹 서비스 만들기] Ch03 STATE | 4. State Functions (0) | 2022.05.17 |