Cute Bow Tie Hearts Blinking Pink Pointer

프론트엔드/React

[React] 버튼 누를 때마다 숫자 증가, 감소하는 카운터 만들기

청포도 에이드 2022. 4. 13. 17:33
728x90
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
    <div id="root"></div>
    <script type="text/babel">

        class Counter extends React.Component{

            state = {
                number:0
            }
            incre = (index)=>{
                const increase = {
                    ...this.state,
                    number:this.state.number + index
                }

                this.setState(increase)
            }

            decre = (index)=>{
                const decrease = {
                    ...this.state,
                    number:this.state.number -index
                }
                this.setState(decrease)
            }

            render(){
                return(
                    <div>
                        <h3>{this.state.number}</h3>
                        <button onClick={ ()=>{ this.incre(2)} }>+</button>
                        <button onClick={ ()=>{ this.decre(2)}}>-</button>
                    </div>
                )
            }
        }

        class App extends React.Component{
            render(){
                return(
                    <div>
                        <Counter/>
                    </div>
                )
            }
        }

        ReactDOM.render(
            <App/>,
            document.querySelector('#root')
        )


    </script>
</body>
</html>
728x90