객체도 속성으로 전달이 가능합니다.
|
컴포넌트 호출
let users = [ {id:1, name:"한사람",age:18},
{id:2, name:"두사람",age:22},
]
<WelcomePropsClass user={users[0]}/>
<WelcomePropsFunction user={users[1]}/>
컴포넌트에 전달된 객체 {"user":{"id":1,"name":"한사람","age":18}} {"user":{"id":2,"name":"두사람","age":22}} |
1. create-react-app를 이용하여 app004 프로젝트를 만듭니다.
1) 프로젝트 작성 D:\React> npx create-react-app app004 2) 폴더이동 D:\React> cd app004 3) visual code 실행 D:\React\app004> code . 4) public 폴더와 src폴더의 모든 파일을 삭제합니다. |
2. public 폴더에 다음과 같이 index.html파일을 생성합니다.
|
1
2
3
4
5
6
7
8
9
10
11
|
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Component</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
|
3. src폴더에 WelcomePropsFunction.js 파일을 다음과 같이 만듭니다.
|
1
2
3
4
5
6
7
8
9
10
|
let WelcomePropsFunction = (props) =>{
console.log(JSON.stringify(props));
let {name, age, gender} = props.user;
return(
<>
<h2>{name}({age}세, {gender ? "남":"여"})님 반갑습니다.</h2>
</>
);
}
export default WelcomePropsFunction;
|
cs |
4. src폴더에 WelcomePropsClass.js 파일을 다음과 같이 만듭니다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
// 컴포넌트 만들기
// ES6의 클래스로 만들기
import React from 'react';
class WelcomePropsClass extends React.Component {
render() {
console.log(JSON.stringify(this.props));
let {name, age, gender} = this.props.user;
return (
<h2>
{name}({age}세, {gender ? "남" : "여"})님 반갑습니다.
</h2>
);
}
}
export default WelcomePropsClass;
|
cs |
5. src폴더에 App.js 파일을 다음과 같이 만듭니다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import WelcomePropsClass from "./WelcomePropsClass";
import WelcomePropsFunction from "./WelcomePropsFunction";
function App(){
let users = [
{id:1, name:"한사람",age:18},
{id:2, name:"두사람",age:22},
]
return (
<>
<WelcomePropsClass user={users[0]}/>
<WelcomePropsFunction user={users[1]}/>
</>
);
}
export default App;
|
cs |
6. src폴더에 index.js 파일을 다음과 같이 만듭니다.
|
1
2
3
4
5
6
7
8
9
10
11
12
|
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css'
import App from './App';
const root = ReactDOM.createRoot(document.querySelector("#app"));
root.render(
<React.StrictMode>
<App/>
</React.StrictMode>
);
|
cs |
7. visual code에서 [새 터미널] 창을 열고 "npm start"명령으로 애플리케이션을 시작합니다.
실행 화면 입니다.

'Front End > React' 카테고리의 다른 글
| [React Exam 20] jQuery 사용하기 (1) | 2024.10.21 |
|---|---|
| [React Exam 19] 스타일 추가하기 (0) | 2024.10.21 |
| [React Exam 17] 컴포넌트(Component)에 값을 속성으로 전달하기 (0) | 2024.10.21 |
| [React Exam 16] 컴포넌트(Component)를 만들어 사용해 보자 (1) | 2024.10.16 |
| [React Exam 15] create-react-app로 Hello World출력하기 (1) | 2024.10.16 |