React Basic - 3. 클래스 컴포넌트의 형태와 리액트 데브 툴즈

Bloooooooooooooog..·2023년 6월 8일
0

규칙

리액트에서 객체를 수정하여 사용하는 것보다는 객체를 복사해서 사용하는 것을 권장한다.

push, pop, shift, unshift, splice와 같이 배열을 직접 변경하는 함수를 사용하는 것도 지양하며, 새로운 배열을 복사해서 수정해야 한다.

// HTML
<div id="root"></div>


=====================================================


    class LikeButton extends React.Component{
        constructor(props){
            super(props);
            this.state = {liked:false};
        }
        render(){
            if(this.state.liked){
                return 'You Liked this.';
            }
		// 원시 형태의 리액트 코드를 주석 시켰다.
           // return React.createElement('button', {onClick: ()=>this.setState({liked:true})}, '뿡빵');
           return(
             // JSX
                <button onClick = 
             // this.state.liked=true와 같이 사용하지 않는다. 
             //(직접 객체 변경을 하지 않기 위해)
             {()=> this.setState({liked:true})
        	// 리액트는 데이터를 바꾸면 화면을 바꾼다. 
        }
      
      >뿡빵</button>
           );
        }

    }
 
    ReactDOM.render(<LikeButton/>, document.querySelector('#root'));

리액트는 데이터가 바뀌면 화면이 바뀐다.
리액트의 이러한 특성을 파악하기 쉽기 위해 Dev Tool을 이용하면 편하다.

리액트 Dev Tool

구글의 React Developer Tool을 설치하면 된다.
확장을 이용해 Profiler와 Components를 이용 가능하다.

  • Profiler는 성능 확인
  • Components는 Component와 State를 확인할 때 사용한다.

리액트 클래스 함수 사용은 점점 변형이 되어가 아래와 같은 형태로 쓰였다.

<script type="text/babel">

    'use strict';

    class LikeButton extends React.Component{

        state = {liked:false};
        

        onClickButton = () =>{
            this.setState({liked : true});
        }

        render(){
            if(this.state.liked){
                return 'You Liked this.';
            }

           // return React.createElement('button', {onClick: ()=>this.setState({liked:true})}, '뿡빵');
           return(
             //this.state.liked=true 처럼 사용할 수 없다. 객체를 함부로 변경하지 마라(불변셩), 바꾸지 말고 복사해서 사용
                <button onClick = {this.onClickButton}>
                뿡빵</button>
           );
        }

    } // 1% ErrorBoundary
</script>
profile
공부와 일상

0개의 댓글

Powered by GraphCDN, the GraphQL CDN