강디너의 개발 일지

React - props 와 state를 이용한 데이터 전달 본문

Javascript/삽질

React - props 와 state를 이용한 데이터 전달

강디너 2019. 4. 30. 23:56
728x90

 

A 컴포넌트에서 B 컴포넌트로 데이터를 전달해보겠습니다.

 

Root 컴포넌트입니다.

user_id 를 A 컴포넌트에서 받는 작업을 먼저 해줍니다.

state = {
	user_id: ''
}

getData = (data) =>{
    this.setState({user_id: data});
}

render(){
	return(
    	<componentA fromParent={this.getData} ></componentA>
    )
}

 

A컴포넌트 입니다.

아래와 같이 해주면 testFunction이 실행될 때 Root의 user_id는 test 로 값이 바뀝니다.

testFunction = () =>{
	this.props.fromParent('test');
}

 

 

B 컴포넌트로 보낼려면 Root 컴포넌트를 수정해야합니다.

componentB 로 user_id를 보냅니다.

state = {
	user_id: ''
}

getData = (data) =>{
    this.setState({user_id: data});
}

render(){
	return(
    	<componentA fromParent={this.getData} ></componentA>
        <componentB id={this.state.user_id}></componentB>
    )
}

B컴포넌트 입니다.

componentWillReceiveProps 를 이용해서 props 를 받으면 실행되게 하는 React Lifecycle 입니다.

componentWillReceiveProps(nextProps){
	// nextProps.id = 'test';
	console.log(nextProps);
}

 

커피한잔...
Comments