1. React 컴포넌트 생성
- amount : 입력된 거리 값
- flipped : 킬로미터와 마일 간 전환 여부
function App() { const [amount, setAmount] = React.useState(0); const [flipped, setFlipped] = React.useState(false);
2. 이벤트 핸들러 작성
- onChange : 입력값이 변경될 때 호출되어 값을 업데이트함
const onChange = (event) => { setAmount(event.target.value); }; const reset = () => setAmount(0); const onFlip = () => { reset(); setFlipped((current) => !current); };
3. JSX를 사용하여 UI 구성
return ( <div> <h1>거리 계산기</h1> <label htmlFor="kilometers">Kilometers</label> <input value={flipped ? (amount / 0.621371) : amount} id="kilometers" placeholder="Kilometers" type="number" onChange={onChange} disabled={flipped} /> <label htmlFor="miles">Miles</label> <input value={flipped ? amount : (amount * 0.621371)} id="miles" placeholder="Miles" type="number" disabled={!flipped} onChange={onChange} /> <button onClick={reset}>초기화</button> <button onClick={onFlip}>전환</button> </div> );
4. ReactDOM을 사용하여 컴포넌트 렌더링
const root = document.getElementById("root"); ReactDOM.render(<App />, root);
<!DOCTYPE html> <html lang="en"> <body> <div id="root"></div> </body> <script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/babel-standalone@6.26.0/babel.min.js"></script> <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>거리 계산기</h1> <label htmlFor="kilometers">Kilometers</label> <input value={flipped ? (amount / 0.621371) : amount} id="kilometers" placeholder="Kilometers" type="number" onChange={onChange} disabled={flipped} /> <label htmlFor="miles">Miles</label> <input value={flipped ? amount : (amount * 0.621371)} id="miles" placeholder="Miles" type="number" disabled={!flipped} onChange={onChange} /> <button onClick={reset}>초기화</button> <button onClick={onFlip}>전환</button> </div> ); } const root = document.getElementById("root"); ReactDOM.render(<App />, root); </script> </html>
Share article