React - Components - 04

React - Components - 04

Structuring Apps with Class-Based Components

Benefits of Class Components

  • 쉬운 코드 구성
  • state 사용 -> 사용자 입력을 처리하기 쉬움
  • 라이프사이클 이벤트 -> 앱을 처음 시작할 때 일을 더 쉽게 수행

Functional vs Class

  • Functional Components: 심플한 콘텐츠에 좋음
  • Class Components: 그 외 모든 것에 좋음

Fules of Class Components

  • 자바스크림트 클래스이어야 함
  • React.Component를 확장해야 함(서브 클래스)
  • JSX를 반환하는 render 메소드를 정의해야 함

Make Components

일반적으로 컴포넌트를 생성할 때에는 React.Component 클래스를 상속하여 만든다.(클래스 기반 컴포넌트에는 많은 메소드가 추가 될 것이므로)
import  React  from  'react';
import  ReactDOM  from  'react-dom';

class  App  extends  React.Component { // this

 render() {
  window.navigator.geolocation.getCurrentPosition(
   (position) =>  console.log(position),
   (err) =>  console.log(err)
  );

  return  <div>Latitude: </div>
 }
}

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

State in React Components

The Rules of State

  • Only usable with class components
  • You will confuse props with state :(
  • ‘State’ is a JS object that contains data relevant to a component
  • Updating ‘state’ on a component causes the component to (almost) instantly rerender
  • State must be initialized when a component is created
  • State can only be updated using the function ‘setState’
    import  React  from  'react';
    import  ReactDOM  from  'react-dom';
    
    class  App  extends  React.Component {
     constructor(props) {
     // Super is a reference to the parent's constructor function and all
      super(props);
    
      // Initialized
      // This is the only time we do direct assignment
      // to this.state
      this.state = { lat:  null, errorMessage:  ''  };
      window.navigator.geolocation.getCurrentPosition(
       position  => {
        console.log(position)
        // We called setState!!
        this.setState({ lat:  position.coords.latitude });
    
        // We did not!!!!
        // this.state.lat = position.coords.latitude
       },
       err  => {
        console.log(err)
        this.setState({ errorMessage:  err.message })
       }
      );
     }
    
     // React says we have to define render!!
     render() {
      return (
       <div>
        Latitude: {this.state.lat}
        <br  />
        Error: {this.state.errorMessage}
       </div>
      );
     }
    }
      
    ReactDOM.render(<App  />, document.querySelector('#root'))
    

Conditionally Rendering Content

render() 메소드에서 if문을 사용하여 화면에 출력되는 문장을 바꿀 수 있다.
render() {
 if (this.state.errorMessage && !this.state.lat) {
  return  <div>Error: {this.state.errorMessage}</div>
 }

 if (!this.state.errorMessage && this.state.lat) {
  return  <div>Latitude: {this.state.lat}</div>
 }

 return  <div>Loading!</div>
}

GitHub and Others

댓글

가장 많이 본 글