ReactNative Navigation Tab 의 Event Listener 받기 / Tab Disabled 만들기

낭만개발자·2021년 10월 1일
0

ReactNative

목록 보기
6/7

문제

RN navigation의 Tab중에 한 탭을 press 할때 페이지 이동을 disable 시키고 싶다...그래서 boolean 의 parameter를 전달해서 받는 페이지에서 조건 분기에서 if문 사용하여 처리하려 했다가, 받는 페이지에서 랜더링 후 initParam이 default 형태로 변하는 바람에 fail..

해결

그래서 API문서를 다시 찾아보기로 함.. RN Navigation API Doc은 제법 많다 ㅠ
보는데 Tab.Navigation의 전체 탭에 event를 리스너로 받을수도 있고, 각 <Tab.Screen> 에서 listeners 처리도 할 수 있었다.

주소 : https://reactnavigation.org/docs/navigation-events

listeners prop on Screen

Sometimes you might want to add a listener from the component where you defined the navigator rather than inside the screen.
때때로, 너는 리스너를 추가하는 걸 원할 수 있다 / 그 컴포넌트로 부터 / 니가 정의한 내비게이터를 / 그 스크린 내부 보다
You can use the listeners prop on the Screen component to add listeners.
너는 listeners prop를 사용할 수 있따아ㅏ/ 스크린 컴포넌트 상에 / 리스너들을 추가하기 위해
The listeners prop takes an object with the event names as keys and the listener callbacks as values.
그 listeners prop하나의 객체를 가진다 / 그 이벤트 명이 키 들로서 / 그 리스너 콜백함수들이 value로서 /

즉 이말임 :

<Tab.Screen
  name="Chat"
  component={Chat}
  listeners={{
    tabPress: (e) => {
      // Prevent default action
      e.preventDefault();
    },
  }}
/>

Tab.Screen에 listeners로 키를 tabPress 주고 value에 콜백함수 주면 된다.
참고로 .prventDefault 한번 찾아 봤는데 이벤트를 취소 시킬수 있는 함수다. 따라서 disabled 시키고 싶으면 걸어주면된다.

You can also pass a callback which returns the object with listeners. It'll receive navigation and route as the arguments.
너는 또한 콜백을 전달 할수 있다 /(어떠한 콜백?) object들을 리턴해주는 콜백 / 리스너들을 가진. / 그것은 받을 것이다 / 네비게이션과 라우트를 / arg로서!!

와우 직역하니 넘 좋다. 앞으로 포스팅할때 직역체로 써야 겠다. ㅎㅎㅎ
example :

<Tab.Screen
  name="Chat"
  component={Chat}
  listeners={({ navigation, route }) => ({
    tabPress: (e) => {
      // Prevent default action
      e.preventDefault();

      // Do something with the `navigation` object
      navigation.navigate('AnotherPlace');
    },
  })}
/>

위에 예제서 param 주고 싶으면 navigate('Place', {paramValName:'value'}) 두번째 navigate 파라미터로 주면 나중에 받는 screen 컴포넌트에서 route.param.paramValName 으로 사용 가능.

내 소스 :

아래 처럼 listeners 에서 tabPress 처리 한뒤 e.preventDefault(); 설정해주면 탭을 눌러도 alert를 띄우며 이동하지 않게(= disabled) 만들 수 있다.

profile
낭만닥터와 슬의를 보고 저런 개발자가 되어야 겠다고 꿈꿔봅니다.

0개의 댓글