Props와 State

Haechan Kim·2022년 1월 30일
0

React

목록 보기
13/13
post-thumbnail
  • Props (properties)
    props는 부모 컴포넌트가 자식 컴포넌트에세 값 전달시 사용한다. 읽기 전용
  1. 클래스형 컴포넌트일때

부모 컴포넌트

import Reaxt, {Component} from 'react';
import Child from './Child';
// App.js 부모 컴포넌트
class App extends Component {
  render() {
    // 자식 컴포넌트(Child) 로 props 값 first, last 전달
    return <Child first = "gildong" last = "Hong" />;
  }
}

export default App;

자식 컴포넌트

import React, {Component} from 'react';
// Child.js 자식 컴포넌트
class Child extends Component {
    render() {
        // 부모로부터 어떤 Object 넘어왔는지 알수있다
        console.log(this);
        // 부모로부터 받은 props
        const {first, last} = this.props;
        return (
            <div>
                이름: {first} {last}
                </div>
        )
    }
}

export default Child;


2. 함수형 컴포넌트일때

부모 컴포넌트

import React from 'react';
import Child from './Child';
// App.js 부모 컴포넌트
const App = () => {
  // 자식 컴포넌트(Child) 로 props 값 first, last 전달
  return <Child first = "gildong" last = "Hong" />;
}

export default App;

자식 컴포넌트

import React from 'react';
// Child.js 자식 컴포넌트
const Child = (props) => {
    return (
        <div>
            이름: {props.first} {props.last}
        </div>
    )
}

export default Child;
  • States
    컴포넌트 자기 자신이 갖고 있는 값.
    클setState, 함useState

=> 더 추가하기

0개의 댓글