propertites이며, 단어의 뜻대로 해당 컴포넌트의 속성값이다. (html
에서 사용했던 attribute
과 비슷하지만, react
의 경우 네이밍을 자유롭게 지정할 수 있다.)
부모 컴포넌트로부터 전달받은 데이터를 props
라는 객체 에 저장하게 된다.(key
, value
)
자식 컴포넌트는 props
를 통해 부모의 state
에 저장된 데이터값과 eventhandler
를 받을 수 있다.
state
는 컴포넌트 자신이 갖고 있는 데이터 창고같은 느낌이라면, props
는 데이터를 전달하는 통로라고 생각하면 편하다.
1. 부모 컴포넌트
import React from "react"; import Child from "./Child"; // export default class Parents extends React.Component { render() { return ( <> <Child data="hello world" /> </> ); } }
2. 자식 컴포넌트
import React from "react"; // export default class Child extends React.Component { render() { return ( <> <div>{this.props.data}</div> </> ); } }
부모 컴포넌트는 data
라는 props
를 통해서, 자식 컴포넌트에게 객체 형식 으로 데이터를 전달하게 된다.
자식 컴포넌트는 props
를 통해 받아온 정보를 사용할 수 있다.
props
의 전달 방향은 항상 단방향(부모 컴포넌트 -> 자식 컴포넌트) 이며 형제 컴포넌트들간의 전달은 불가능하다.
컴포넌트의 상태, 즉 컴포넌트 자신이 갖고 있는, 데이터 및 정보를 담은 객체이다. (props, state 모두 객체 형태로 데이터 저장)
컴포넌트 내에서 정의하고 method를 통해 수정할 수 있으며, props를 통해서 자식 컴포넌트에게 해당 데이터를 전달할 수 있다.
1. 부모 컴포넌트
import React from "react"; import Child from "./Child"; // export default class Parents extends React.Component { constructor(props) { super(props); this.state = { color: "red" }; } render() { return ( <> <Child textColor={this.state.color} content="안녕하세요" /> </> ); } }
2. 자식 컴포넌트
import React from "react"; // export default class Child extends React.Component { render() { return ( <> <div style={{ color: this.props.textColor }}>{this.props.content}</div> </> // 예시를 위해 inline으로 스타일을 지정하였다. ); } }
부모 컴포넌트는 state
라는 객체 안에 color:red
라는 데이터를 저장했으며, textColor
라는 props를 통해 자식 컴포넌트로 데이터를 전달하였다.
자식 컴포넌트는 textColor
를 통해 부모 컴포넌트의 state에 접근하여 color
를 빨간색으로 지정할 수 있었다.