Cute Bow Tie Hearts Blinking Pink Pointer

프론트엔드/React

[React] 버튼 클릭할 때마다 버튼 글씨 바꾸기

청포도 에이드 2022. 4. 13. 17:30
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 Login extends React.Component{

            // constructor(props){
            //     super(props)
            //     this.state = {

            //     }
            // }

            state = {
                //무조건 state라는 변수명이어야 함! 객체여야만 함!!
                isLogin:false
            }

            //state 안에 변수 바꾸려면? setState() //state라는 변수를 바꿔주는 함수임.

            render(){
                // this.setState({
                //     ...this.state,
                //     name:'ingoo2'
                // })

                const obj = {
                    ...this.state,
                    isLogin: !this.state.isLogin
                }
                return(
                    <button onClick={ ()=>{ this.setState(obj) } }>
                        {this.state.isLogin ? '로그아웃': '로그인'}

                    </button>    
                )
            }
        }

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

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

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