Skip to main content

Platform

Platform平台

  • Platform.OS可以取得目前使用者的手機平台
  • 即使是Android,StatusBar的高度還是會有不同,所以也可直接取得目前手機的StatusBar
import{SafeAreaView, Text, StyleSheet, StatusBar, Platform} from 'react-native';
const MyScreen = () => {
return (
<SafeAreaView style={styles.container}>
<Button title="Click Me" onPress={ () => alert('Button Pressed!') } />
</SafeAreaView>
);
}

const styles = StyleSheet.create({
container: {
flex:1,
backgroundColor:"#FFF",
paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
}
});

Dimensions尺寸

  • 取得手機Screen的高度寬度
import{SafeAreaView, Text, StyleSheet, StatusBar, Platform, Dimensions} from 'react-native';
const MyScreen = () => {
console.log(Dimensions.get("screen"));
return (
<SafeAreaView style={styles.container}>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
container: {
backgroundColor:"dodgerblue",
width:"50%",
height:70,
}
});

Orientation方向

  • 先到app.json,修改orientation值
...
"orientation": "default", //可同時支援landscape及portrait
...
  • 安裝react native hooks, 這裡的useDimensions可以支援不同orientation
npm install @react-native-community/hooks
  • 取得手機Orientation及尺寸
import{SafeAreaView, Text, StyleSheet, StatusBar, Platform} from 'react-native';
import { useDeviceOrientation, userDimensions } from '@react-native-community/hooks';
const MyScreen = () => {
const orientation = useDeviceOrientation();
console.log(orientation);
return (
<SafeAreaView style={styles.container}>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
container: {
backgroundColor:"dodgerblue",
width:"100%",
height: "30%"
}
});

應用:當orientation是landscape時,顯示全螢幕

import{SafeAreaView, Text, StyleSheet, StatusBar, Platform} from 'react-native';
import { useDeviceOrientation, userDimensions } from '@react-native-community/hooks';
const MyScreen = () => {
const {landscape} = useDeviceOrientation();
return (
<View>
style={
backgroundColor:"dodgerblue",
width:"100%",
height: landscape ? "100%" : "30%",
}
</View>
);
}