TIL 23 | React State, Props, Event

song hyun·2021년 8월 23일
1

React

목록 보기
3/12
post-thumbnail

이 글에서는 아래와 같은 것을 정리한다.
1. props의 개념에 대해 설명
2. state의 개념에 대해 설명
3. state를 이용해서 UI를 구성
4. 이벤트를 통해 state를 변경
5. props를 이용해 부모 요소의 state를 자식 요소에 반영하는 것 설명.
6. props를 개념을 이용해 자식에서 일어난 이벤트로 부모의 state 값을 변경하는 것 설명.

Props

Props 외부 전달 받은 읽기 전용 속성.

// App.js
import Child from "./Child";
import React, { Component } from "react";

class App extends Component {
  render() {
    return (
      <>
    <Child msg="hello, wecode" />
    <Child data="21/08/21"/>
    </>
    );
  }
}

export default App;
// Child.js
import React, {Component} from "react";
class Child extends Component{
  render(){
    return(
      <>
        <h1>{this.props.msg}</h1>
        <span>{this.props.data}</span>
      </>

    )
  }
}

State

state는 UI를 구성하는 요소로 모든 컴포넌트 state를 가지고 있고 state를 변경할 수 있다. 이처럼 컴포넌트 state의 생성 그리고 업데이트 제거 된 이러한 값들을 관리한다.

// App.js
import Child from "./Child";
import React, { Component } from "react";

class App extends Component {
  constructor(props){
    super(props);
      this.state={
        msg:"hello, wecode",
        name:"hyun"
      };
    }
  render() {
    // console.log() 확인 
    return (
      <>
    <Child msg={this.state.msg} name={this.state.name}  />
    </>
    );
  }
}

export default App;

setState

React는 DOM 기반에서 이제 state 기반으로 동작하게 한다. 😁

컴포넌트 state의 값을 변경하기 위한 메서드.

// Child.js
import React, { Component } from "react";

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "hyun"
    };
  }
     
  changeName = () => {
    // state를 인자로 전달하면 기존 state와 병합.
    this.setState({
      name: "jun"
    });
  };
  render() {
    console.log(this.state);
    return (
      <>
        <h1>Hello, {this.state.name}</h1>
        <button type="button" onClick={this.changeName}>
          on/off
        </button>
  		<Child subname={this.state.name}  />
      </>
    );
  
  }
}

export default Child;

Event

부모 컴포넌트에서 state를 자식 컴포넌트 전달해줬을 때, 자식은 그 state를 props로 전달 받는다. 부모에 state가 변경되면, 자식도 변경된 props를 반영한다.

profile
Front-end Developer 🌱

0개의 댓글