FrontEnd/React
[ReactJS] prop에 대한 이해
kurooru
2023. 1. 8. 15:13
다음 코드의 흐름을 이해해보자
<!DOCTYPE html>
<html lang="en">
<body>
<div id="root"></div>
</body>
<!-- How to import React(engine) -->
<script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
<!-- How to import React-dom(put elements into HTML) -->
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
<!-- How to make browser read JSX syntax (using babel)-->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
const root = document.getElementById("root");
function App () {
// React.useState(default value)
const [amount, setAmount] = React.useState(0);
const [flipped, setFlipped] = React.useState(false);
const onChange = (event) => {
setAmount(event.target.value);
};
const reset = () => {
setAmount(0);
};
// reset and flip current (true->false / false->true)
const onFlip = () => {
reset();
setFlipped((current) => !current);
};
return (
<div>
<h1>Super Converter</h1>
<div>
<label htmlFor="minutes">Minutes</label>
<input
// if we are flipped show amount with 60 times
// if we are not flipped show amount
value={flipped ? amount * 60 : amount}
id="minutes"
placeholder="Minutes"
type="number"
onChange={onChange}
// opposite one from hours
disabled={flipped}
/>
</div>
<div>
<label HtmlFor="hours">Hours</label>
<input
// if we are filpped -> show amount
// if we are not filpped -> show amout divided with 60
value={flipped ? amount : Math.round(amount/60)}
id="hours"
placeholder="Hours"
type="number"
// opposite one from minutes
disabled={!flipped}
onChange={onChange}
/>
</div>
<button onClick={reset}>reset</button>
<button onClick={onFlip}>Flip</button>
</div>
)
}
// initial render
ReactDOM.render(<App />, root);
</script>
</html>
이전과 마찬가지로 브라우저는 initial rendering을 실행하고 App함수를 root id 안에 렌더링한다.
살펴볼 것은 사용자가 Flip 버튼을 눌렀을 때 일어나는 일이다.
Flip 함수를 click하게 되면 onClick 반응에 의해 onFlip 함수가 실행된다.
onFlip 함수는 reset 함수를 실행하고, setFlipped함수를 실행하는데,
reset함수는 입력받은 값들을 0으로 되돌리는 함수이다.
그리고 setFlipped함수는 current 즉 flipped의 스위치를 끄고 키듯 true와 false로 변환시킨다.
여기서 current가 flipped에 해당하는 이유는 useState() 매서드를 사용했기 때문에 둘은 연동되어 움직인다.
그러면 flipped의 상태는 처음에 flase라는 default 값에서 출발하여, true로 바뀌게 되는데,
이 때에 바뀐 값을 가지고 rerendering이 일어난다.
HTML의 disabled 속성 즉 input 박스를 굳히는 속성에서 minutes와 hours는 서로 반대로 반응하고,
처음에는 굳어있던 hours가 풀리고 이번에는 minutes가 굳게 된다.
그리고 나타나는 값 또한 '?'문을 이용하여 hours에 적은 값은 현재 flipped가 true인 상태이므로 amount로 나타나고,
minutes에서는 flipped가 true인 상태이므로 amount에 60배를 곱한 값으로 나타난다.
후 어지러워