Props : 컴포넌트 외부에서 컴포넌트에게 주는 데이터
State : 컴포넌트 내부에서 변경할 수 있는 데이터
둘 다 변경이 생기는 경우 render(컴포넌트 그리는 방법을 기술하는 함수)가 다시 일어날 수 있음.
Function Component (default)props 사용
function Component(props) { return ( <div> <h1>{props.message} 이것은 함수로 만든 컴포넌트</h1> </div> ) } ReactDom.render( <Component message="안녕하세요" />, document.querySelector('#root') ); Component.defaultProps={ message : "기본값" }
Class Component (default)props 사용
class Component extends React.Component { render() { return ( <div> <h1>{this.props.message} 이것은 클래스로 만든 컴포넌트</h1> </div> ); } static defaultProps = { message:"기본값2," } }
Class Component에서 state 사용
class Component extends React.Component { //state 정의 첫번째 방법 state = { count=0, }; //state 정의 두번째 방법 constructor(props) { super(props); this.state = { count: 0 }; } render() { return ( <div> <h1>{this.props.message} 이것은 클래스로 만든 컴포넌트</h1> <p>{this.state.count}</p> </div> ); } //state 변화 첫번째 방법 componentDidMount() { setTimeout(() => { this.setState({ count: this.state.count + 1, }); }, 1000); } //state 변화 두번째 방법 componentDidMount() { setTimeout(() => { this.setState((previousState) => { const newState = { count: previousState.count + 1 }; return newState; }); }, 1000); } }
Class Component에서 Event Handling
// 1. 첫 번째 방법 constructor(props) { super(props); this.click = this.click.bind(this); } render() { return ( <div> <h1>{this.props.message} 이것은 클래스로 만든 컴포넌트</h1> <button onClick={this.click}>클릭</button> </div> ); } click() { console.log("clicked"); this.setState((state) => ({ ...this.state, count: this.state.count + 1, })); } // 2. 두 번째 방법 click = () => { console.log("clicked"); this.setState((state) => ({ ...this.state, count: this.state.count + 1, })); }