엄코딩의 개발 일지

React Native( 이하 RN ) 개발을 시작하면서 처음 난관에 부딫쳤던 에러가 있다.

 

개발해야 하는 피쳐는 아래와 같다.

 

rootView안에 FlatList에서 사용하는 CustomView가 존재한다. 이 CustomView에 TouchableOpacity를 씌우고 onPress시에 

 

detail 화면으로 이동해야한다. 이전까지 너무 쉬웠던 navigate였기에 방심했던걸까..

 

우선 에러는 다음과 같다.

 

 

undefined is not an object... stackoverflow를 열심히 뒤져 보아도 모두 같은 내용일 뿐 해결되지 않았다. ( 너무 기본이라서 나오지 않았던 걸까...? )

 

constructor에 bind하는 방법이며, rootView에서 navigation을 넘겨주는 방법이며... 다 내가 찾던 방법이 아니었다.

 

그래서 ReactNative Document를 차근차근 읽어보던중 해법을 찾았다.

 

this.props.navigation

 

It's important to highlight the navigation prop is not passed in to all components; only screen components receive this prop automatically! React Navigation doesn't do anything magic here. For example, if you were to define a MyBackButton component and render it as a child of a screen component, you would not be able to access the navigation prop on it. If, however, you wish to access the navigation prop in any of your components, you may use the withNavigation HOC.

 

- 루트를 설정할 때 연결했었던 Screen에는 자동으로 navigation props가 전달된다.

 

- 직접적으로 설정되어 있지 않은 경우 react-navigation이 제공해주는 HOC 컴포넌트를 인자로 호출해서 직접 주입해줘야 한다.

 

import { withNavigation } from 'react-navigation';

class SubComponent extends React.Component {
	...
}

export default withNavigation(SubComponent);

 

진행하고 있던 프로젝트에서 FlatList의 ItemView를 클릭시 DetailView로 이동했어야 했는데, 해당 ItemView는 SubComponent였지만 위 코드처럼 HOC 컴포넌트를 인자로 호출해서 직접 주입하지 않았다.

그래서 에러가 발생했었고, 위 코드처럼 HOC 컴포넌트를 인자로 호출해서 직접 주입해주니 WORKING !!