Project/사이드 프로젝트

[React Native(RN)] Stack Screen 헤더 스타일 설정과 오류 해결 (backgroundColor, fontSize, color, fontWeight, headerShadowVisible, options 오류 메시지)

아밍나 2024. 9. 20. 23:59
728x90

- 사용 언어: Typescript

- 사용한 라이브러리: @react-navigation/native-stack

npm install @react-navigation/native-stack

코드

Stack Screen의 헤더를 커스텀하기 위한 코드를 작성했습니다.

options에서 설정을 적용하면 되는데, 적용할 설정이 많아서 options를 따로 선언해주었습니다.

import { createNativeStackNavigator } from "@react-navigation/native-stack";

type StackParamList = {
    Screen1: undefined;
    Screen2: undefined;
}

const Stack = createNativeStackNavigator<StackParamList>();

return (
    <Stack.Navigator>
        <Stack.Screen
            name="Screen1"
            component={FirstScreenComponent}
            options={headerOption({title: "첫 번째 화면"}) />
        <Stack.Screen
            name="Screen2"
            component={SecondScreenComponent}
            options={headerOption({title: "두 번째 화면"}) />
    </Stack.Navigator>
)

 

- 적용된 options (헤더 배경색, 제목, 글자 크기, 글자 색, 글자 굵기, 헤더 그림자)

const headerOption = ({title}:{title: string}) => {
    return ({
        headerTitle: title, 
        headerStyle: { 
          backgroundColor: BG_COLOR,
        },
        headerTitleStyle: {
          fontSize: 18,
          color: team.teamColor,
          fontWeight: "bold" //"200", "300", "600", "800" 그 외
        },
        headerShadowVisible: false
  })};

헤더의 제목만 따로 설정해주기 위해 파라미터 값으로 받아오고, 헤더 배경색, 제목, 글자 색, 글자 크기, 글자 굵기를 설정하고, 헤더 그림자를 제거하는 코드입니다.

에러

이때 오류가 발생합니다. 실행하고 옵션이 모두 적용되지만 options에 빨간 줄이 뜹니다.

원인

원인은 바로 "fontWeight".

오류 메시지가 굉장히 길게 나오지만, fontWeight가 원인임은 다음 문장으로 알 수 있습니다.

Types of property 'fontWeight' are incompatible.

 

React Native는 UI에서 동작하는 속성을 문제없이 렌더링하지만 Typescipt는 타입을 엄격하게 확인하기 때문에 스타일은 적용되지만 오류 메시지가 발생하는 것입니다.

해결

Typescipt의 타입 경고를 피하기 위해 fontWeight의 타입을 강제로 변환해줍니다.

fontWeight: "bold" as TextStyle['fontWeight']

 

오류 메시지가 사라집니다.


다른 스타일도 적용하고 싶다면, 아래 링크를 참조하시면 됩니다.

https://reactnavigation.org/docs/headers/

 

Configuring the header bar | React Navigation

We've seen how to configure the header title already, but let's go over that again before moving on to some other options — repetition is key to learning!

reactnavigation.org

 

728x90
반응형