본문으로 바로가기

React Props와 State의 차이

category JavaScript/React 2022. 4. 15. 21:43
반응형

https://ko.wikipedia.org

<"리액트를 다루는 기술" 책 참조>


Props란

- properties를 줄인 표현

- 컴포넌트 자신은 해당 props를 읽기 전용으로 사용

- 컴포넌트 속성을 설정할 떄 사용하는 요소

- props 값은 해당 컴포넌트를 불러와 사용하는 부모 컴포넌트에서 설정 가능.

 

부모 컴포넌트 App.js

import React from 'react';
import MyComponent from './MyComponent';

const App = () => {
	return <MyComponent name="React" />;
};

default export App;

자식 컴포넌트 MyComponent.js

import React from 'react';

const MyComponent = props => {
	return <div>안녕하세요, 제 이름은 {props.name}입니다.</div>;
};

export default MyComponent;

 

 

State란

- 컴포넌트 내부에서 변경 가능

- State가 변경되면 컴포넌트를 다시 렌더링 해야함

- 클래스형 State, 함수형 useState 함수

 

부모 컴포넌트 App.js

import React from 'react';
import Say from './Say';

const App = () => {
	return <Say />;
};

export default App;

자식 컴포넌트 Say.js

import React, { useState } from 'react';

const Say = () => {
	const [message, setMessage] = useState('');
    const onClickEnter = () => setMessage('안녕하세요');
    const onClickLeave = () => setMessage('안녕히 가세요');
    
    return (
    	<div>
        	<button onClick={onClickEnter}> 입장 </button>
        	<button onClick={onClickLeave}> 퇴장 </button>
        	<h1>{message}</h1>
    	</div>
	);
};

export default Say;

 

반응형