ReactNative APIs

seunghye jo·2024년 5월 16일
0

ReactNative

목록 보기
6/8
post-thumbnail

핵심 APIs

  • 하위 API들은 기본적으로 ‘react-native’에서 제공 됨.
  • import { ... } from 'react-native'
    전체 API는 공식문서 참고

Alert

  • Alert.alert()
    • Native Alert Dialog(경고창) 생성.

      alert(
      	title:string, 
      	message?: string, 
      	button?: {
      		text: string
      		style: "cancel" | "defult" | "destructive"
      		onPress: function
      		...
      	}[],
      	options?: AlertOptions
      )

Platform

  • 앱이 동작하는 기기의 플랫폼에 대한 정보 반환
  • Platform.OS
    • 구동중인 기기의 운영체제 반환.
    • android | ios | macos | web | windows
      console.log(Platform.OS) // 'android'
      console.log(Platform.OS) // 'ios'
  • Platform.select()
    • 플랫폼 별 반환값을 설정
      const styles = StyleSheet.create({
        container: {
          flex: 1,
          ...Platform.select({
            android: {
              backgroundColor: 'green',
            },
            ios: {
              backgroundColor: 'red',
            },
            default: {
              backgroundColor: 'blue',
            },
          }),
        },
      });

Dimensions

  • 앱이 동작하는 기기의 화면 정보(너비, 높이 …) 반환 함수
  • .get(dim: "window" | "screeen")
    • IOS 에서는 "window""screen" 의 차이가 없음
    • Android
      • "screen" : 상태표시줄을 포함한 화면 정보
      • "window" : 상태표시줄을 제외한 화면의 정보
const deviceWidth = Dimensions.get("window").width // 상태표시줄을 제외한 화면의 너비
const deviceHeight = Dimensions.get("window").height // 상태표시줄을 제외한 화면의 높이

// StyleSheet 내에서 활용 가능
const styles = StyleSheet.create({
	customStyle: {
		width: deviceWidth - 16,
		height: deviceHeight / 3
	}
})
  • 앱 실행 시 최초 한번만 실행되기 때문에, 중간에 화면의 크기가 바뀌어도 변하는 값을 알 수 없음. 해당 단점 보완을 위해 useWindowDismensions 사용 권장

useWindowDismensions

  • 기기의 화면 정보(너비, 높이 …)를 반환하는 훅
  • 화면의 정보가 변할 때마다 값이 업데이트 됨
const MyComponent = () => {
	const { width, height } = useWindowDimensions()
	
	const customWidth = width - 16
	
	return (
		// 스타일 병합을 통해 값 전달
		<View style={[styles.customStyle, { width: customWidth }]}>
			...
		</View>
	)
}

const styles = StyleSheet.create({
	customStyle: {
		...
	}
})
profile
프론트엔드 개발자 성장일기 💭

0개의 댓글