본문 바로가기
깃허브 링크!
react

로그인 로그아웃(리액트 구현 웹 페이지)

 

React.Component도 컴포넌트야?

ChatGPT
네, 정확히 말하면 React.Component는 리액트에서 제공하는 기본적인 컴포넌트 클래스입니다. 
React.Component를 상속받아서 새로운 컴포넌트를 정의하고 사용할 수 있습니다.

React.Component는 리액트에서 컴포넌트를 작성하기 위한 기본적인 구조와 메서드를 제공합니다.
이를 상속받은 클래스는 리액트 컴포넌트로서의 기능과 생명주기 메서드를 사용할 수 있게 됩니다.
따라서, React.Component를 상속받은 클래스를 정의하는 것은 새로운 컴포넌트를 생성하는 것과
동일한 개념입니다.

따라서, React.Component는 자체적으로도 하나의 컴포넌트로 볼 수 있으며,
이를 상속받아 새로운 컴포넌트를 작성할 수 있습니다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
        <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
    <div id="root"></div>
</body>
<script type="text/babel">
    class TEXT extends React.Component{
        constructor(props){
            super(props);
        }

        render(){
            return <h2>{this.props.text}</h2>
        }
    }

    class LoginBtnText extends React.Component {
        constructor(props){
            super(props);
            console.log(props);
        }

        render(){
            return this.props.flag ? <TEXT text="로그아웃"/> : <TEXT text="로그인"/>
        }
    }

    class LoginBtn extends React.Component {
        constructor(props){
            super(props);
            this.state = {
                isLogin : false
            }
            // bind 메서드로 바인딩하면 함수 호출할때 컨텍스트를 유지할수 있다.
            // 리액트에서 유용하게 쓸수 있음.
            this.handleClick = this.handleClick.bind(this);
        }

        handleClick(){
            this.setState({isLogin : !this.state.isLogin})
        }

        render(){
            return (<button onClick={this.handleClick}>
                <LoginBtnText flag={this.state.isLogin} />    
                </button>
            )
        }
    }

    class App extends React.Component {
        constructor(props){
            super(props)
            this.state = {
                isLogin : false
            }
        }

        render(){
            return(<>
            <TEXT text="로그인 로그아웃 "/>
            <LoginBtn />
            </>
            )
        }
    }

    // 루트 요소 생성
    // 루트로 설정
    const root = ReactDOM.createRoot(document.querySelector('#root'));
    root.render(<App />);
</script>
</html>

 

 

 

 

※ React component를 상속받는 이유

React에서 제공하는 컴포넌트 클래스를 기반으로 사용자 정의 컴포넌트를 생성하기 위함

 

React 컴포넌트 클래스를 상속받으면 해당 클래스는 React 컴포넌트로서 동작할수 있는 기능과 생명주기 메서드를 상속받는다.

 

- 생명주기 메서드란

React 컴포넌트의 생성, 업데이트 , 소멸과 관련된 단계에서 호출되는 메서드들을 말한다.

 

예시로 하나 들자면

componentDidMount(): 컴포넌트가 화면에 마운트된 후(렌더링된 후) 호출되는 메서드입니다.
이 때 주로 초기 데이터 로딩, 외부 라이브러리 초기화 등의 작업을 수행합니다.



React Component를 상속받으면 그냥 내재되어있음

 

 

 

LoginBtnText 컴포넌트는 로그인 버튼에 표시될 텍스트를 제공하기 위한 컴포넌트

LoginBtn 컴포넌트는 로그인 상태에 따라 텍스트를 변경하여 렌더링해야 한다.

 

 class LoginBtnText extends React.Component {
        constructor(props){
            super(props);
            console.log(props);
        }

        render(){
            return this.props.flag ? <TEXT text="로그아웃"/> : <TEXT text="로그인"/>
        }
    }

- LoginBtnText 컴포넌트는 로그인 버튼에 표시될 텍스트를 제공하기 위한 컴포넌트

flag = 'prop'값에 이름을 지어줌 내 생각에 flag가 true or false boolean 역할을 하는듯하다.

 

flag 값이 true 인 경우 로그아웃 / false인 경우 로그인 

 

따라서 LoginBtn 컴포넌트에서 LoginBtnText 컴포넌트를 사용하여 로그인 버튼의 텍스트를 동적으로 변경하고 표시

 <LoginBtnText flag={this.state.isLogin} />

 

 

※ 

<script type="text/babel">
    class TEXT extends React.Component{
        constructor(props){
            super(props);
        }

        render(){
            return <h2>{this.props.text}</h2>
        }
    }

여기에서 this는 TEXT 컴포넌트의 인스턴스를 참조 = React.Component를 참조

 

 

 

 

※ 'text' prop은 'TEXT' 컴포넌트에 전달되는  속성

class TEXT extends React.Component{
        constructor(props){
            super(props);
        }

        render(){
            return <h2>{this.props.text}</h2>
        }
    }

this.prop.text를 통해 'text' prop의 값을 가져온다.

 

class LoginBtnText extends React.Component {
        constructor(props){
            super(props);
            console.log(props);
        }

        render(){
            return this.props.flag ? <TEXT text="로그아웃"/> : <TEXT text="로그인"/>
        }
    }

예를 들어 <TEXT text ="로그아웃"/>와 같이 TEXT 컴포넌트를 사용할 때 text prop에 "로그아웃"값을 전달하면 

해당 컴포넌트에서는 <h2> 태그 안에 "로그아웃"이라는 텍스트가 표시된다.

 

이렇게 컴포넌트에 전달되는 속성을 prop이라고 부르며

부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달하고자 할때 사용된다.

 

 

 

 

-1 render 부분

class LoginBtnText extends React.Component {
        constructor(props){
            super(props);
            console.log(props);
        }

        render(){
            return this.props.flag ? <TEXT text="로그아웃"/> : <TEXT text="로그인"/>
        }
    }

-2 render 부분

 class LoginBtn extends React.Component {
        constructor(props){
            super(props);
            this.state = {
                isLogin : false
            }
            // bind 메서드로 바인딩하면 함수 호출할때 컨텍스트를 유지할수 있다.
            // 리액트에서 유용하게 쓸수 있음.
            this.handleClick = this.handleClick.bind(this);
        }

        handleClick(){
            this.setState({isLogin : !this.state.isLogin})
        }

        render(){
            return (<button onClick={this.handleClick}>
                <LoginBtnText flag={this.state.isLogin} />    
                </button>
            )
        }
    }

2번째 코드식에

LoginBtn 컴포넌트의 상태인 isLogin은 버튼을 클릭했을 때 변화하고 업데이트되는 값입니다. 이 값은 LoginBtn 컴포넌트의 state에서 관리되며, handleClick 메서드를 통해 업데이트됩니다.

버튼 내부에는 LoginBtnText 컴포넌트가 렌더링되고 있는데 flag prop을 받아 해당 값에 따라 다른 내용을 렌더링한다.

 

초기에 LoginBtn 컴포넌트의 상태인 isLogin은 false로 설정되어 있지만 handleClick 메서드를 통해 이 상태를 업데이트 가능하다.

 

 


※ 컴포넌트를 생성하는 이유

코드의 재사용성과 모듈화를 증가

컴포넌트는 독립적이고 재사용 가능한 UI요소를 나타냄

 

React에서는 onclick대신에 handleClick을 사용했는데 일반적으로 handle를 사용할뿐 handle접두사는 필수적이지 않으며 다른 이름을 사용해도 괜찮음 

 

 

 

 

 

'react' 카테고리의 다른 글

react 가위바위보  (0) 2023.07.05
react를 활용한 달력 만들기  (0) 2023.07.04
React 초기 세팅 과정  (0) 2023.07.03
댓글창 만들기(리액트)  (0) 2023.06.29
바닐라js로 리액트 맛보기  (0) 2023.06.28