본문 바로가기
Web/React

03. Counter, Input, useState

by 사라리24 2024. 5. 16.
SMALL

 

1. Counter 컴포넌트

  

 

  • Cmder 실행
  
       < Cmder >
 
       cd 경로
       yarn create react-app counter
       cd counter
       yarn start
 
  
 1. 경로이동
 2. 앱생성
 3. 앱 경로로 이동
 4. yarn 시작

 

 

  • Counter.js 생성
 
 
      < Counter.js >
 
 
            import React from "react";

            function Counter() {
                return (
                    <div>
                        <h1>0</h1>
                        <button>+1</button>
                        <button>-1</button>
                    </div>
                );
            }

            export default Counter;
 
 
  

 

 

  • App.js 수정
  
      < App.js >
 
 
        import React from "react";
        import Counter from "./Counter"

        function App() {
          return (
            <Counter/>
          );
        }

        export default App;
 
  
 

 


 

  • Counter.js
 
 
      < Counter.js >

 
            import React from "react";

            function Counter() {

                const onIncrease = () => {
                    console.log('+1');
                }

                const onDecrease = () => {
                    console.log('-1');
                }

                return (
                    <div>
                        <h1>0</h1>
                        <button onClick={onIncrease}>+1</button>
                        <button onClick={onDecrease}>-1</button>
                    </div>
                );
            }

            export default Counter;
 
 
  

 

 

 

  • Counter.js
  
 
      < Counter.js >

 
            import React from "react";

            function Counter() {

                let number = 0;

                const onIncrease = () => {
                    number++;
                    console.log('+1');
                }

                const onDecrease = () => {
                    number--;
                    console.log('-1');
                }

                return (
                    <div>
                        <h1>{number}</h1>
                        <button onClick={onIncrease}>+1</button>
                        <button onClick={onDecrease}>-1</button>
                    </div>
                );
            }

            export default Counter;
  
 


실제 화면에서 number  값에 반영되지 않음

 

 

  • Counter.js
  
 
      < Counter.js >

            import React from "react";

            function Counter() {

                let number = 0;

                const onIncrease = () => {
                    number++;
                    console.log('+1');
                    console.log(number);
                }

                const onDecrease = () => {
                    number--;
                    console.log('-1');
                    console.log(number);
                }

                return (
                    <div>
                        <h1>{number}</h1>
                        <button onClick={onIncrease}>+1</button>
                        <button onClick={onDecrease}>-1</button>
                    </div>
                );
            }

            export default Counter;
 
  
콘솔에서는 number 값이 반영되어 찍히기는 함


 

  • Counter.js
  
 
      < Counter.js >


        import React, {useState} from "react";

        function Counter() {

            // let number = 0;
 
            const [number, setNumber ] = useState(0);
            // const [변수, 함수] = useState(초기화하고 싶은 값)
            // 값이 변할 때마다 화면이 갱신됨
            // 사용자 X 리액트 가상돔에서 변경O

            const onIncrease = () => {
                // number++;
                // console.log(number);
                setNumber(number + 1);
                console.log('+1');

            }

            const onDecrease = () => {
                //number--;
                //console.log(number);
                setNumber(number - 1);
                console.log('-1');
            }

            return (
                <div>
                    <h1>{number}</h1>
                    <button onClick={onIncrease}>+1</button>
                    <button onClick={onDecrease}>-1</button>
                </div>
            );
        }

        export default Counter;
 
 
  
 

상태를 관리하는 함수 (use.state) 를 사용하면 화면 {number} 에도 반영되게 할 수 있음


 


 

 

2. 입력 필드와 초기화 버튼 구현하기(1)

  


🔽
 기본화면구성

  • Input.js 생성
 
      < Input.js >

 
            import React from "react";

            function Input(){
                return (
                    <div>
                        <input/>
                        <button>초기화</button>
                        <div>
                            <b>값: </b>
                        </div>
                    </div>
                );
            }

            export default Input;
 
  

 

 

  • App.js
  
      < App.js >

 
 
        import React from "react";
        import Input from "./Input";

        function App() {
          return (
            <Input/>
          );
        }

        export default App;
  

 


🔽 Text 입력값이 화면에 뜨게하고, 초기화 눌렀을 때 초기화되게 하기

  • Input.js 
  
       < Input.js >
 
 
 
            import React, { useState } from "react";


            function Input(){

                const [text, setText] = useState("");

                const onChange = (e) => {
                    setText(e.target.value);
                };

                const onReset = () => {
                    setText("");
                };

                return (
                    <div>
                        <input value={text} onChange={onChange} />
                        <button onClick={onReset}>초기화</button>
                        <div>
                            <b>값:</b> {text}
                        </div>
                    </div>
                );
            }

            export default Input;
 
 
 
  

입력필드의 값이 화면에 동일하게 뜸



버튼을 누르면 값이 초기화됨

 

 



3. 입력 필드와 초기화 버튼 구현하기(2)

  

 

 

🔽 기본화면구성

  • MultiInput.js 생성
 
 
       < MultiInput.js >

 
            import React, {useState} from "react";

            function MultiInput() {
                const onChange = (e) => {

                }
                const onReset = (e) => {

                }
               
                return (
                    <div>
                        <input placeholder="아이디"/>
                        <input placeholder="이름"/>
                        <button onClick={onReset}>초기화</button>
                        <div>
                            <b>값: </b>
                            아이디(이름)
                        </div>
                    </div>
                )
            }
 
  

 

 

  • App.js 수정
  
       < App.js >
 
 
        import React from "react";
        import MultiInput from "./MultiInput"

        function App() {
          return (
            <MultiInput/>
          );
        }

        export default App;
  
 

 

 

🔽아이디와 이름 입력값이 화면에 뜨게하고, 초기화 눌렀을 때 '동시에' 초기화되게 하기

  • MultiInput.js 
 

       < MultiInput.js >
 
 
            import React, {useState} from "react";

            function MultiInput() {

                const [inputs, setInputs] = useState({
                    userid: '',
                    name: ''
                });

                const { userid, name } = inputs; // 비구조화 할당을 통해 값 추출

                const onChange = (e) => {
                    const { name, value } = e.target; // e.target에서 name과 value 추출
                    setInputs({
                        ...inputs, // 기존의 inputs 객체를 복사한 뒤
                        [name]: value // name 키를 가진 값을 value로 설정
                    });
                }

                const onReset = (e) => {
                    setInputs({
                        userid: '',
                        name: ''
                    });
                }
               
                return (
                    <div>
                        <input name="userid" value={userid} placeholder="아이디" onChange={onChange}/>
                        <input name="name"  value={name} placeholder="이름" onChange={onChange}/>
                        <button onClick={onReset}>초기화</button>
                        <div>
                            <b>값: </b>
                            {userid} ({name})
                        </div>
                    </div>
                )
            }

            export default MultiInput;
 
 
  


 



4. Counter 활용

  

 

  • 문제) 아래와 같은 카운터 프로그램을 작성해보자

 

  • TotalCounter.js 생성
  
 
      < TotalCounter.js  >

 
 
            import React, {useState} from "react";


            function TotalCounter() {

                const [inputs, setInputs ] = useState({
                    number1: 0,
                    number2: 0
                });

                const { number1, number2 } = inputs;

                const onIncrease = (name) => {
                    setInputs({
                        ...inputs,
                        [name]: inputs[name] + 1
                    });
                }
                const totalCount = () => {
                    return number1 + number2;
                };

                const onReset = (e) => {
                    setInputs({
                        number1: 0,
                        number2: 0
                    });
                }


                return (
                    <div>
                        <div>
                            <h1>Total Count: {totalCount()}</h1>
                        </div>
                        <div>
                        <h1>{number1}</h1>
                        <button onClick={() => onIncrease('number1')}>add</button>
                    </div>
                    <div>
                        <h1>{number2}</h1>
                        <button onClick={() => onIncrease('number2')}>add</button>
                    </div>
                    <br></br>
                    <button onClick={onReset}>초기화</button>
                    </div>
                );
            }

            export default TotalCounter;
 
  

 

  • App.js
 
      < App.js >

 
        import React from "react";
        import TotalCounter from "./TotalCounter"

        function App() {
          return (
            <TotalCounter/>
          );
        }

        export default App;
 
  
 

 

 


🔽 다른 방법으로 구현

 

  • conponents 폴더 생성 > Counter.jsx 생성
  
      < Counter.jsx >

 
            import React, {useState} from "react";

            export default function Counter({total, onClick}){
               
                const [count, setCount] = useState(0);
                return (
                    <div className="counter">
                        <p className="number">
                            {count} <span className="total">/{total}</span>
                        </p>
                        <button className="button" onClick={() => {
                            setCount((prev) => prev + 1);
                            onClick();
                        }}>+1</button>
                    </div>
                );
            }
 
 
  

 

 

  • App.js -> Appcounter.jsx 로 변경
 
      < Appcounter.jsx >

 

        import Count from "./components/Count.jsx";
        import React, {useState} from "react";
        import "./App.css";

        export default function AppCounter() {
          const [count, setCount] = useState(0);
          const handleClick = () => setCount((prev) => prev + 1);
          return (
            // <Counter/>
            // <Input/>
            // <MultiInput/>
            <div className="container">
              <div className="banner">
                TotalCount: {count}
              </div>
              <div className="counters">
                <Count total={count} onClick={handleClick}/>
                <Count total={count} onClick={handleClick}/>
              </div>
            </div>
          );
        }
 
  

 

  • index.js 수정
  
      < index.js >

 
        import React from 'react';
        import ReactDOM from 'react-dom/client';
        import './index.css';
        import AppCounter from './AppCounter'; //수정
        import reportWebVitals from './reportWebVitals';

        const root = ReactDOM.createRoot(document.getElementById('root'));
        root.render(
          <React.StrictMode>
            <AppCounter /> //수정
          </React.StrictMode>
        );

        // If you want to start measuring performance in your app, pass a function
        // to log results (for example: reportWebVitals(console.log))
        // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
        reportWebVitals();
 
  
 

 

  • App.css

  
      <App.css >

 
        .container{
          width: 600px;
          margin: auto;
        }
        .banner{
          text-align: center;
          margin-top: 5rem;
          font-size: 2rem;
          background-color: gold;
          font-weight: bold;
        }
        .counter{
          display: flex;
          flex-direction: column;
          align-items: center;
          margin: 2rem;
          padding: 1rem;
          border-radius: 1rem;
          border: 2px solid orange;
        }
        .counter:hover{
          background-color: ivory;
        }
        .number{
          font-size: 3rem;
        }
        .button{
          font-size: 2rem;
          padding: 0.2rem, 1rem;
          border-radius: 0.5rem;
          cursor: pointer;
          background-color: orange;
        }
        .total{
          font-size: 1rem;
          margin-left: 0.5rem;
        }
 
 
  

 


 

🔽 기능추가

- TotalCount의 값이 10보다 작으면 👎 출력, 10보다 크면 👍출력

 

  •  Appcounter.jsx 수정
 
 
      < Appcounter.jsx >
 

        import Count from "./components/Count.jsx";
        import React, {useState} from "react";
        import "./App.css";

        export default function AppCounter() {
          const [count, setCount] = useState(0);

          const handleClick = () => setCount((prev) => prev + 1);

          return (

            <div className="container">
              <div className="banner">
                TotalCount: {count} {count > 10 ? '👍':''}
              </div>
              <div className="counters">
                <Count total={count} onClick={handleClick}/>
                <Count total={count} onClick={handleClick}/>
              </div>
            </div>
          );
        }
 
  


10 이하일 때 👎



11 이상일 때 👍

 

'Web > React' 카테고리의 다른 글

05. useEffect, 웹소켓  (0) 2024.05.17
04. 배열 데이터 활용, useRef  (0) 2024.05.16
02. 컴포넌트에 값 전달하기  (0) 2024.05.13
01. React, 컴포넌트 생성  (0) 2024.05.13