[RN] react-native navigation params 사용하기

2024. 8. 28. 14:51·React Native
반응형

🐰: RN은 알다가도 모르겠고,

모르겠다가도 알거같은.....

 

navigation을 아직 완전히 이해하지는 못했지만

오늘 새롭게 사용한 함수를 잊기 전에 기록해두러 왔다 !

 

 

Params란?

화면을 구성할 때 함께 전달되는 매개변수(parameters)를 의미한다.

 

 

Params 사용하기

params를 사용하기 위해서는 두 가지 과정이 있어야 한다.

 

1. navigation.navigate() 함수의 두 번째 변수로 params를 전달해야 한다.

navigation.navigate('RouteName', { /* params go here */ })

params는 JSON직렬화가 가능한 형태를 추천한다.(보통 객체 형태로 전달한다.)

 

2. Screen의 구성요소에서 params를 읽어야 한다.

function ScreenName({ route }) {
  /* route.params 으로 사용할 수 있다. */
}

 

 

 

Params 함수

1. setParams()

현재 화면의 매개변수를 동적으로 업데이트 및 이미 활성화된 화면의 'route' 파라미터를 업데이트 할 수 있다.

navigation.setParams({
  query: 'someText',
});

 

setParams() 사용 예

  useEffect(() => {

    if (NoticeDetail?.data) {
      const ContentsRe = {
        category: NoticeDetail?.data.category,
        title: NoticeDetail?.data.title,
        isNotice: NoticeDetail?.data.isNotice,
        contents: `<html style="margin:0;padding:0;"><meta name="viewport" content="width=device-width, user-scalable=no">
                <body style="margin:0;padding:0;">${NoticeDetail.data.contents}</body></html>`,
        regDate: NoticeDetail?.data.regDate,
        viewCnt: NoticeDetail?.data.viewCnt,
        id: NoticeDetail?.data.postIdx,
      };
      setcontents(ContentsRe);
      
      // 여기서 현재 화면의 route params에 ContentsRe 객체를 NoticeDetail이라는 키로 추가 또는 업데이트
      navigation.setParams({ NoticeDetail: ContentsRe });
    }
  }, [NoticeDetail]);

 

 

2. initialParams

화면이 처음 렌더링될 때 기본적으로 제공되는 매개변수를 설정합니다. 이 매개변수들은 해당 화면에서 route.params로 접근할 수 있다.

<Stack.Screen
  name="Details"
  component={DetailsScreen}
  initialParams={{ itemId: 42 }}
/>

 

initialParams() 사용 예

  <Stack.Screen
    options={{
      header: tabheader,
    }}

    //화면이 처음으로 렌더링될 때 title이라는 매개변수를 'notice'로 설정하겠다는 의미
    initialParams={{ title : 'notice' }}

    name="noticeList"
    component={Noticelist}
  />

 

 

3. navigate()

일부 데이터를 새 화면에 전달할 때 뿐만 아니라 이전 화면에 데이터를 전달하는 데 사용할 수도 있다.

(게시글 작성 페이지에서 게시글을 작성하고, 게시글에 대한 데이터 전달)

 

 

 

[참고]

https://reactnavigation.org/docs/params/

 

Passing parameters to routes | React Navigation

Remember when I said "more on that later when we talk about params!"? Well, the time has come.

reactnavigation.org

 

반응형

'React Native' 카테고리의 다른 글

[RN] react-native button으로 sort 정렬하기  (0) 2024.09.06
[RN] react-native tab navigation 스크린 이동 새로고침  (0) 2024.08.28
[RN] reanimated failed to create a worklet react native.. error  (0) 2024.08.23
[RN] react-native UseEffect (()=> {},[]); 사용법  (0) 2024.06.25
[RN] react-native 댓글태그 지우기, Comments Tag remove, Back Space  (0) 2024.06.24
'React Native' 카테고리의 다른 글
  • [RN] react-native button으로 sort 정렬하기
  • [RN] react-native tab navigation 스크린 이동 새로고침
  • [RN] reanimated failed to create a worklet react native.. error
  • [RN] react-native UseEffect (()=> {},[]); 사용법
nicee
nicee
답을 찾아가는 과정이 즐거운 프론트엔드 개발자의 기록모음🧐
    반응형
  • nicee
    나의 개발일지
    nicee
  • 글쓰기 관리
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Project01 [Chat App]
      • React Native
      • Git
      • Program Setting
      • nicee-day
      • Study
        • C++
  • 블로그 메뉴

    • 링크

      • 🌳 git키우기
      • 📚 일상기록
    • 공지사항

    • 인기 글

    • 태그

      k직장인
      불금
      rn
      c++
      Android
      error
      React
      firebase
      타입스크립트
      Xcode
      직장인짤
      APP
      채팅앱
      티스토리챌린지
      공부
      typescript
      백준코딩테스트
      리액트네이티브
      빌드에러
      k직장인일상
      앱개발
      React-native
      커피수혈
      next.js
      리액트
      nextjs
      app build
      오블완
      IOS
      에러해결
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    nicee
    [RN] react-native navigation params 사용하기
    상단으로

    티스토리툴바