DEV/react
React 시작하기 2. Props
석봉
2023. 12. 15. 18:48
Props
Properties는 component에 데이터를 전달하기 위해 사용됩니다.
1. src/App.js
import React from 'react';
import Sample from './Sample';
function App() {
return (
<div>
<Sample text="This is " name="react" />
</div>
);
}
export default App;
2. src/Sample.js
// 컴포넌트 생성을 위해 React Import
import React from 'react';
/**
* [Props sample]
* @param {*} props 전달 데이터
* @returns
*/
function Sample(props) {
return <div>{props.text} {props.name} sample component!!</div>
}
// 컴포넌트 내보내기 (다른 컴포넌트에서 불러오기 위해!!)
export default Sample;
또는
// 컴포넌트 생성을 위해 React Import
import React from 'react';
/**
* [Props sample]
* @param {*} props 전달 데이터
* @returns
*/
function Sample({text, name}) {
return <div>{text} {name} sample component!!</div>
}
// 컴포넌트 내보내기 (다른 컴포넌트에서 불러오기 위해!!)
export default Sample;
defaultProps
props를 넘겨주지 않았을 때, 기본적으로 적용되는 값
1. src/Sample.js
// 컴포넌트 생성을 위해 React Import
import React from 'react';
/**
* [Props sample]
* @text {*} 전달 데이터
* @name {*} 전달 데이터
* @returns
*/
function Sample({text, name}) {
return <div>{text} {name} sample component!!</div>
}
Sample.defaultProps = {
name: 'nothing',
}
// 컴포넌트 내보내기 (다른 컴포넌트에서 불러오기 위해!!)
export default Sample;
2. src/App.js
import React from 'react';
import Sample from './Sample'; // Sample component 불러오기
function App() {
return (
// 아까 작성한 Sample component 사용
<div>
<Sample text="This is " />
</div>
);
}
export default App;
props.children
Component tag 사이에 무언가 넣고 싶은 경우
1. src/Sample.js
// 컴포넌트 생성을 위해 React Import
import React from 'react';
/**
* [Props sample]
* @children {*} <div 2개 넣었지롱>
* @returns
*/
function Sample({ children }) {
const style = {
border: '5px solid red',
padding: '10px',
}
return <div style={style}>{children}</div>
}
// 컴포넌트 내보내기 (다른 컴포넌트에서 불러오기 위해!!)
export default Sample;
2. src/App.js
import React from 'react';
import Sample from './Sample'; // Sample component 불러오기
function App() {
return (
// 아까 작성한 Sample component 사용
<div>
<Sample>
<div>SAMPLE</div>
<div>CODE</div>
</Sample>
</div>
);
}
export default App;