Dimensionsを利用するときは、
import {View, Text, Dimenstions } from 'react-native'
のように記載して利用する。
まず、ドキュメントを読んでみよう。
そこのサンプルコードを利用し、スマホを縦にしたときと横にしたときに
レイアウトを変更するコードを作成してみる。
例えばボタンなんかでは、縦長では縦に並べたいが、横にしたときにも縦だと、ボタンが横長になりすぎたりするので、横に並べたいことがあるかと思われる。
app.jsonの 'expo'の'orientation'については、下記のようにしておく
"orientation": "undefined"
App.js
import React, {useState, useEffect} from 'react';
import {View, StyleSheet, Text, Dimensions} from 'react-native';
const windowDimensions = Dimensions.get('window');
const screenDimensions = Dimensions.get('screen');
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
const App = () => {
const [dimensions, setDimensions] = useState({
window: windowDimensions,
screen: screenDimensions,
});
const [windowSize, setWindowSize] = useState({
height: windowHeight,
width: windowWidth,
})
<Text style={styles.header}>Screen Dimensions</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
},
containerPortrait: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
},
containerLandscape: {
flexDirection: 'row',
justifyContent: 'center',
alignItems:'center'
},
header: {
fontSize: 16,
marginVertical: 10,
},
});
export default App;
*1:) => {
const subscription = Dimensions.addEventListener(
'change',
({window, screen, height, width}) => {
setDimensions({window, screen});
setWindowSize({height, width});
},
);
return () => subscription?.remove();
});
return (
<View style={styles.container}>
<View style={ windowSize.height> windowSize.width ? styles.containerPortrait : styles.containerLandscape}>
<Text style={styles.header}>Window Dimensions</Text>
<Text>
</Text>
<Text>
</Text>