세로 및 가로 방향의 다양한 레이아웃

동기 부여



나는 앱이 세로 방향과 가로 방향의 두 가지 다른 레이아웃을 가져야 하는 프로젝트에서 일한 적이 없습니다. 그래서 호기심 때문에 이 기능을 가진 간단한 프로젝트를 만들기로 했습니다.

프로젝트



프로젝트는 앱이 세로 방향일 때 다음 레이아웃을 갖게 되는 로그인 화면으로 구성됩니다.



앱이 가로 방향일 때 다음 레이아웃을 갖게 됩니다.



코딩하자




import  React,{useState, useEffect} from 'react';
import { Text, View, StyleSheet, TextInput, Image, KeyboardAvoidingView, ScrollView, SafeAreaView, Dimensions } from 'react-native';
import Constants from 'expo-constants';
import AssetExample from './components/AssetExample'


export default function App() {
  const [isVerticalOrientation, setIsVerticalOrientation] = useState(true)
  const [firstInputText, setFirstInputText] = useState('Orientation')
  const [secondInputText, setSecondInputText] = useState('Width')
  const [thirdInputText, setThirdInputText] = useState('Height')

  const checkIfDeviceIsInVerticalOrHorizontalOrientation = () =>{
  const screenWidth = Dimensions.get('window').width
  const screenHeight = Dimensions.get('window').height
    if(screenWidth > screenHeight){
        setIsVerticalOrientation(false)
    }else{
        setIsVerticalOrientation(true)
    }
  }

  return (
    <View onLayout={()=>checkIfDeviceIsInVerticalOrHorizontalOrientation()} style={!isVerticalOrientation ?  styles.containerRow : styles.container}>
       <AssetExample/>
       <View>
        <TextInput value={firstInputText} style=      {styles.inputStyle} onChangeText={(text)=> setFirstInputText(text)}/>
        <TextInput style={styles.inputStyle}  value={secondInputText}/>
        <TextInput style={styles.inputStyle}  value={thirdInputText}/>
    </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ACACAC',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 8,
  },
   containerRow: {
    flex:1,
    flexDirection: 'row',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ACACAC',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 8,
  },
  inputStyle: {
    borderWidth: 1,
    borderColor: 'white',
    width: 200,
    height:50,
    borderRadius: 50,
    paddingLeft:10,
    marginTop:10,
  },
});


"checkIfDeviceIsInVerticalOrHorizontalOrientation"메서드를 사용하여 기본 컨테이너의 onLayout을 체크인합니다.
화면의 너비가 높이보다 크면 기기가 가로 방향이고 그렇지 않으면 기기가 세로 방향입니다.
각 조건에서 값에 따라 레이아웃이 "container"또는 "containerRow"라는 스타일로 변경되는 "isVerticalOrientation"이라는 상태를 설정했습니다. 이러한 스타일은 레이아웃이 가로 또는 세로처럼 작동해야 하는지 여부를 결정하므로 기본 스타일입니다.


앱의 전체 코드: https://github.com/gabrielsideprojects/awesome-device-orientation
풀 리퀘스트 및 제안에 열려 있습니다. 편히 쉬세요😃.
Snack을 사용하여 앱을 만들었습니다. 원하는 경우 내 snack를 확인하고 실행하여 작동하는지 확인할 수 있습니다 🔳.
the social network you desire 😃☕에서 포근하고 따뜻한 커피 마시며 인사해요.

좋은 웹페이지 즐겨찾기