본문 바로가기

Front End/React

[React Exam 17] 컴포넌트(Component)에 값을 속성으로 전달하기

작성한 컴포넌트에 속성값을 지정해서 전달이 가능합니다.

함수형 컴포넌트에서는 props라는 매개변수를 사용함으로서 사용이 가능해 집니다.

클래스형 컴포넌트에서는 this.props라는 변수를 사용함으로서 사용이 가능해 집니다.  

 

전달된 속성은 객체로 전달이 됩니다.

           컴포넌트 호출
            <WelcomePropsClass name="한사람" age={21} gender={true}/>
            <WelcomePropsFunction name="두사람" age={18} gender={false}/>


           컴포넌트에 전달된 객체
           {"name":"한사람","age":21,"gender":true}
           {"name":"두사람","age":18,"gender":false}

 

주의할 사항은 자료형을 유지하려면 표현식을 {}안에 전달해야 합니다. 따옴표안에 전달할 경우에는 무조건 문자열로 판단합니다.

 

 

1. create-react-app를 이용하여 app003 프로젝트를 만듭니다.


1) 프로젝트 작성
D:\React> npx create-react-app app003

2) 폴더이동
D:\React> cd app003

3) visual code 실행
D:\React\app003> 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
let WelcomePropsFunction = (props) =>{
    console.log(JSON.stringify(props));
    return(
        <>
            <h2>{props.name}({props.age}세, {props.gender ? "남":"여"})님 반갑습니다.</h2>
        </>
    );
}
export default WelcomePropsFunction;
cs

 

4. src폴더에 WelcomePropsClass.js 파일을 다음과 같이 만듭니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';
 
class WelcomePropsClass extends React.Component {
    render() {
        console.log(JSON.stringify(this.props));
        return (
            <h2>
                {this.props.name}({this.props.age}세, {this.props.gender ? "남":"여"})님 반갑습니다.
            </h2>
        );
    }
}
export default WelcomePropsClass;
cs

 

5. src폴더에 App.js 파일을 다음과 같이 만듭니다.

1
2
3
4
5
6
7
8
9
10
11
12
import WelcomePropsClass from "./WelcomePropsClass";
import WelcomePropsFunction from "./WelcomePropsFunction";
 
function App(){
    return (
        <>
            <WelcomePropsClass name="한사람" age={21} gender={true}/>
            <WelcomePropsFunction name="두사람" age={18} gender={false}/>
        </>
    );
}
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"명령으로 애플리케이션을 시작합니다. 

 

실행 화면 입니다.