Last active
January 28, 2019 03:04
-
-
Save sdymj84/2eda5d66daa66d8865b8637d902d81e6 to your computer and use it in GitHub Desktop.
[Blog] React 에서 Child Component 에서 Parent Component 로 select 태그 옵션 전달하기!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ChildComp extends React.Component { | |
state = { | |
favFlaver: "", | |
} | |
// 2. 요 handleChange 에서 선택된 옵션값을 가져오고 setState! | |
handleChange(event) { | |
this.setState({ favFlaver: event.target.value }); | |
} | |
render() { | |
return ( | |
// 1. 여기서 유저가 option을 선택하면 onChange가 트리거되서 위의 handleChange 를 호출하죠 | |
// 3. 그리고 나서 state에서 가져온 값을 밑의 value에 적용시킴으로서 실제 UI가 바뀌게 됨 | |
<select value={this.state.value} onChange={this.handleChange}> | |
<option value="grapefruit">Grapefruit</option> | |
<option value="lime">Lime</option> | |
<option value="coconut">Coconut</option> | |
<option value="mango">Mango</option> | |
</select> | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class ParentComp extends Component { | |
state = { | |
favFlaver: "", | |
} | |
handleFavFlaverChange = (favFlaver) => { | |
this.setState({ favFlaver: favFlaver }) | |
} | |
render() { | |
return ( | |
<Container> | |
// 1. onChange 라는 이름으로 props를 ChildComp로 보냄 | |
// 그러면 Child에서 props.onChange를 호출 할 시 위 handleFavFlaverChange 콜백함수가 실행됨 | |
<ChildComp onChange={this.handleFavFlaverChange} /> | |
</Container> | |
) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ChildComp | |
// 1. Parent로 부터 받은 props인 onChange를 통해 selected option인 event.target.value를 보냅 | |
handleChange(event) { | |
this.setState({ favFlaver: event.target.value }); | |
this.props.onChange(event.target.value) | |
} | |
// ParentComp | |
// 2. 그러고 Parent에서는 favFlaver를 받아서 | |
handleFavFlaverChange = (favFlaver) => { | |
this.setState({ favFlaver: favFlaver }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment