리액트 - Component & props & state

HELLO WORLD🙌·2020년 5월 9일
0

TIL

목록 보기
3/23

컴포넌트

Function Component는 function이고 뭔가를 return 하고 screen에 표시된다.
Class component는 class이지만 react component로부터 확장되고 screen에 표시된다. 그것을 render메소드안에 넣어야한다.

함수로 Welcome 컴포넌트 구현하기

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

class로 Welcome 컴포넌트 구현하기

class로 컴포넌트를 만드려면 React.Component 를 extend해서 생성한다. 컴포넌트를 생성할 때 render() 메서드는 무조건 정의해야하고, return도 해주어야 한다.

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Props

정의한 컴포넌트를 사용할 때, 원하는 attribute를 얼마든지 추가할 수 있다.
=> 프로퍼티의 줄임말인 props라고한다.
그러면 Welcome 컴포넌트(함수)에서 parameter로 해당 attribute를 받아서 사용할 수 있다.

// 1. Welcome 컴포넌트 정의
function Welcome(props) {
 return <h1>Hello, {props.name}</h1>;
}

// 2. App 컴포넌트 정의
function App() {
 return (
   <div>
     <Welcome name="Sara" />
     <Welcome name="Cahal" />
     <Welcome name="Edite" />
   </div>
 );
}

// 3. 화면에 React 요소 그려주기
ReactDOM.render(
 <App />,
 document.getElementById('root')
);

State

리액트는 자동적으로 모든 클래스 컴포넌트의 render 메소드를 실행한다.
그렇다면 class컴포넌트를 만드는 이유는? 클래스 컴포넌트가 가지는 state 때문이다.
state는 객체이고 component의 데이터를 넣을 공간이 있고 이 데이터는 변한다.

setState

state의 상태는 직접 값을 바꾸면 안된다. 만약 직접 바꾼다면 리액트는 render메소드를 refresh하지 않기때문이다. 이 말의 의미는 매번 state를 변경할때마다 render function을 호출해서 바꿔줘야 한다는 것이다.

그러기 위해서 setState를 사용한다. state는 객체기때문에 새로운 state 객체를 받아와야한다

class App extends React.Component {
  state = {
    count: 0
  };
  add = () => {
    this.setState(current => ({ count: current.count + 1 }));  
    // this.setState({count : this.state.count + 1}); 와 결과가 같은 코드이지만, 외부의 코드에 의존하지 않도록 개선한코드이다.
  };
  minus = () => {
    this.setState(current => ({ count: current.count - 1 }));
  };
  render() {
    return (
      <div>
        <h1>The number is: {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    );
  }
}

0개의 댓글