[TIL][React] Props / State

ddoni·2020년 12월 28일
2

Props

  1. 개념

모든 컴포넌트는 props 라고 불리는 것을 가지고 있다. 컴포넌트의 props는 하나의 객체(전달된 정보를 저장하는 객체)인데 컴포넌트에 대한 정보를 가지고 있다. this.props 는 저장 객체를 언급하는 것이다.

✨ 하나의 전달된 정보는 prop이라 불린다.

//this.props 표현으로 props에 접근 할 수 있다
render() {
  console.log("Props object comin' up!");
 
  console.log(this.props);
 
  console.log("That was my props object!");
 
  return <h1>Hello world</h1>;
}
  1. 컴포넌트에 props 전달하기

컴포넌트 인스턴스에 attribute 값을 주는 방법으로 리액트 컴포넌트에 정보를 전달 할 수 있다.

(1) 정보를 전달하기 위해 컴포넌트 인스턴스 attr name을 원하는 대로 정한다 (2) JS형식을 전달하고 싶으면 {} 안에 써준다.

//정보를 전달할 컴포넌트 내에 attr를 추가함으로써 원하는 정보를 전달할 수 있다.
<Greeting name="Frarthur" town="Flundon" age={2} haunted={false} />
  1. 전달된 props 보여지게 하기

(1) 정보를 받게될 컴포넌트 클래스 찾기

(2) 컴포넌트 클래스의 렌더 메소드의 리턴에 this.props.name-of-information 추가하기

import React from 'react';
import ReactDOM from 'react-dom';

class Greeting extends React.Component {
  render() {
    return <h1>Hi there, {this.props.name}!</h1>;
  }
}

ReactDOM.render(
  <Greeting name='Groberta' />, 
  document.getElementById('app')
);
  1. 다른 컴포넌트에서 props 전달하기

props의 가장 흔한 사용은 다른 컴포넌트에서 다른 컴포넌트로 정보를 전달하는 것이다.

//App.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Greeting} from './Greeting';

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>
          Hullo and, "Welcome to The Newzz," "On Line!"
        </h1>
//Greeing 에 전달하게 될 정보를 attr에 추가하여 전달
        <Greeting name="Cindy" />
        <article>
          Latest newzz:  where is my phone?
        </article>
      </div>
    );
  }
}

ReactDOM.render(
  <App />, 
  document.getElementById('app')
);

//Greeing.js
import React from 'react';

export class Greeting extends React.Component {
  render() {
//Greeing 클래스 렌더 메소드에 전달된 props에 접근
    return <h1>Hi there, {this.props.name}!</h1>;
  }
}
  1. prop으로써 이벤트핸들러 전달하기

(1) 컴포넌트 클래스 내 이벤트 핸들러 정의하여 전달할 컴포넌트 인스턴스에 attr 값으로 추가

(2) 이벤트가 일어날 컴포넌트 클래스에 이벤트 추가하고 값으로 전달된 props 받아오기

✨ event naming convention

이벤트 메소드의 이름은 handle + event type

이벤트 메소드를 전달할 컴포넌트 인스턴스의 attr name에는 on + event type (이는 실제 이벤트가 발생하지 않는 props name일뿐이다.)

//Talker.js
class Talker extends React.Component {
  handleClick() {
    let speech = '';
    for (let i = 0; i < 10000; i++) {
      speech += 'blah ';
    }
    alert(speech);
  }
  
  render() {
    return <Button onClick={this.handleClick}/>;
  }
}

ReactDOM.render(
  <Talker />,
  document.getElementById('app')
);

//Button.js
export class Button extends React.Component {
  render() {
    return (
      <button onClick={this.props.handlerClick}>
        Click me!
      </button>
    );
  }
}
  1. this.props.children

모든 컴포넌트의 props 객체는 children 이라는 프로퍼티를 가지고 있다. this.props.children 는 JSX 태그의 오프닝과 클로징 태그 사지에 있는 모든것을 리턴한다.

  1. Default Props

className.defalutProps = {} 형태로 기본 props 값을 전달 할 수 있다.

class Example extends React.Component {
  render() {
    return <h1>{this.props.text}</h1>;
  }
}
 
// Set defaultProps equal to an object:
Example.defaultProps = {};

State

  1. 개념

리액트 컴포넌트는 다이나믹한 정보에 propsstate 를 이용하여 접근할 수 있다.

외부에서 정보가 전달되는 props와 달리 state는 컴포넌트가 결정한다.

stateconstructor 메소드 내에 정의해준다

  1. 컴포넌트의 스테이트에 접근하기

this.state 를 이용하여 state에 접근 할 수 있다

class TodayImFeeling extends React.Component {
  constructor(props) {
    super(props);
    this.state = { mood: 'decent' };
  }
 
  render() {
    return (
      <h1>
        I'm feeling {this.state.mood}!
      </h1>
    );
  }
}
  1. state 업데이트하기

컴포넌트는 this.setState(object that will be update the component's state, ?callback) 함수를 호출함으로써 state 를 변경한다. this.setState() 를 호출하는 가장 흔한 방법은 커스텀 함수를 만들어 내부에 this.setState() 를 넣어주는 것이다.

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { weather: 'sunny' };
//makeSomeFog 함수가 this에 접근할 수 있도록 추가해준다.
    this.makeSomeFog = this.makeSomeFog.bind(this);
  }
 
  makeSomeFog() {
    this.setState({
      weather: 'foggy'
    });
  }
}

0개의 댓글