티스토리 뷰
React Navigation 사이트 에서 참고한 내용입니다.
withNavigation 은 감싸고 있는 컴포넌트에 navigation prop 를 전달해주는 Higher-Order 컴포넌트이다. 이는 navigatio prop 를 컴포넌트로 직접 전달할 수 없거나, 깊게 중첩된 자식 컴포넌트로 전달하고 싶지 않을때 유용하다.
This file contains hidden or 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
import React from 'react'; | |
import { Button } from 'react-native'; | |
export default class MyBackButton extends React.Component { | |
render() { | |
// 여기서 navigation prop 가 undefined 이므로 'undefined is not a function' 에러가 발생한다. | |
return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />; | |
} | |
} | |
이를 해결하기 위해선, MyBackButton 에 navigation prop 를 전달하면 된다 :
<MyBackButton navigation={this.props.navigation} />.
또는, withNavigation 를 함수를 이용해 navigation prop 를 자동으로 제공해줄 수 있다. 이 함수는 Redux의 connect 함수와 비슷하게 동작하는데, dispatch prop 대신 navigation prop 를 전달한다.
This file contains hidden or 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
import React from 'react'; | |
import { Button } from 'react-native'; | |
import { withNavigation } from 'react-navigation'; | |
class MyBackButton extends React.Component { | |
render() { | |
return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />; | |
} | |
} | |
// withNavigation 은 navigation prop를 전달하고, MyBackButton 컴포넌트를 리턴한다. | |
export default withNavigation(MyBackButton); | |
이 방법을 통해, navigation prop 를 전달하지 않고 앱 어디에서나 MyBackButton 을 사용할 수 있다.
Kakao 다음웹툰 / 웹표준 및 ft기술, 웹접근성 / 세아이 아빠, 제주 거주 중..
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday