출처: https://www.codecademy.com

props

모든 컴포넌트들은 props 라는 객체를 가지고 있으며, props는 컴포넌트의 정보를 담고있다.

아래 코드와같이 접근하여 props 를 확인할 수 있다

    render() {
      console.log("Props object comin' up!");
    
      console.log(this.props);
    
      console.log("That was my props object!");
    
      return <h1>Hello world</h1>;
    }

Pass props to a Component

component로 어떤 정보를 넘겨주기 위해서는 속성 을 사용한다.

    <컴포넌트이름 속성name="infomation" />

    <컴포넌트이름 속성name={["top", "secret", "lol"]} />

.

    
    // 사용 예
    import React from 'react';
    import ReactDOM from 'react-dom';
    
    class PropsDisplayer extends React.Component {
      render() {
      	const stringProps = JSON.stringify(this.props); //JSON형태로 props를 나타내줌
    
        return (
          <div>
            <h1>CHECK OUT MY PROPS OBJECT</h1>
            <h2>{stringProps}</h2>
          </div>
        );
      }
    }
    
    
    ReactDOM.render(<PropsDisplayer myProp="Hello"/>, document.getElementById('app'))

실행결과

Render a Component’s props

속성을 사용해 컴포넌트의 props객체로 정보를 넘겨보았으니, 넘겨준 값을 확인해보자.

this.props.속성name 을 리턴함으로서 확인 가능

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    class Greeting extends React.Component {
      render() {
        return <h1>Hi there, {this.props.firstName}!</h1>;
      }
    }
    
    ReactDOM.render(
      <Greeting firstName='Thor' />, 
      document.getElementById('app')
    );

실행화면 Hi there, Thor! 라는 문구가 출력됨

Pass props From Component To Component

React에서는 서로다른 컴포넌트간의 props 정보를 주고받는것이 빈번하게 이루어진다.

아래 Greeting.js 와 App.js 가 어떻게 서로 정보를 주고받는지 살펴보자

// App.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    import { Greeting } from './Greeting'; // Greeting 컴포넌트에서 인삿말 부분을 사용할 것이므로 import
    
    class App extends React.Component {
      render() {
        return (
          <div>
            <h1>
              Hullo and, "Welcome to The Newzz," "On Line!"
            </h1>
            <Greeting name="Alison" signedIn={true} />  // Greeting 컴포넌트로 name, signedIn 속성값을 넘겨줌
            <article>
              Latest:  where is my phone?
            </article>
          </div>
        );
      }
    }
    
    ReactDOM.render(
      <App />, 
      document.getElementById('app')
    );

.

//Greeting.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    export class Greeting extends React.Component {
      render() {
      	if (this.props.signedIn == false) {  //전달받은 signedIn 정보가 true라면 인사말과 함께 name을 리턴하고, false라면 GO AWAY를 리턴
      	  return <h1>GO AWAY</h1>;
      	} else {
      	  return <h1>Hi there, {this.props.name}!</h1>;
      	}      }
    }

실행결과