props 는 컴포넌트에서 사용 할 데이터 중 변동되지 않는 데이터를 다룰 때 사용됩니다.
parent 컴포넌트에서 child 컴포넌트로 데이터를 전할 때, props 가 사용된다.
props 추가하기
컴포넌트에서 변동되지 않는 데이터가 필요 할 땐,
render() 메소드의 내부에 안에 { this.props.propsName } 형식으로 넣고,
컴포넌트를 사용 할 때, < > 괄호 안에 propsName="value" 를 넣어 값을 설정한다.
Header 컴포넌트와 Content 컴포넌트가 props를 사용하도록 업데이트 해보면,
props 값이 렌더링 될 위치에 { this.props.propsName } 를 넣습니다.
import React from 'react';
class Header extends React.Component {
render(){
return (
<h1>{ this.props.name }</h1>
);
}
}
export default Header;
import React from 'react';
class Content extends React.Component {
render(){
return (
<div>
<h2>{ this.props.name }</h2>
<p> { this.props.body } </p>
</div>
);
}
}
export default Content;
props 사용하기
App 컴포넌트에도 props 를 넣어주고, App 컴포넌트에서 사용되는 props 값을 child 컴포넌트들로 전달해보면,
App.js
import React from 'react';
import Header from './Header';
import Content from './Content';
class App extends React.Component {
render(){
return (
<div>
<Header title={ this.props.headerName }/>
<Content title={ this.props.contentName }
body={ this.props.contentBody }/>
</div>
);
}
}
export default App;
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
const rootElement = document.getElementById('root');
ReactDOM.render(<App headerName = "Welcome!"
contentName = "Stranger,"
contentBody = "Welcome to example app"/>, rootElement);
'리액트(React) > 리액트에 관련된 정보와 문법들' 카테고리의 다른 글
왜 Hook 을 사용해야할까? (0) | 2021.09.02 |
---|---|
리액트 라이프사이클이란? (0) | 2021.09.02 |