앱개발 2주차

yy N·2022년 10월 8일
0

나는 아직도 뭐가 뭔지 모르겠다....후

앱화면 js 문법에 대해서 기록해놓기로 했다

- 11) `<View>`

👉 <View></View>

화면의 영역(레이아웃)을 잡아주는 엘리먼트입니다. 현재 `App.js` 상에서 `View`는 화면 전체 영역을 가집니다. 우리는 이 `View` 엘리먼트로 다음과 같이 화면을 원하는 대로 분할 할 `수도 있습니다.

- **[코드스니펫] View**
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.subContainerOne}></View>
      <View style={styles.subContainerTwo}></View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  subContainerOne: {
    flex:1,
    backgroundColor:"yellow"
  },
  subContainerTwo: {
    flex:1,
    backgroundColor:"green"
  }
});```

- 12) `<Text>`
    
    👉 앱에 글을 작성하려면 반드시 사용해야하는 엘리먼트입니다. 
    방금전 위에서 배운 View 엘리먼트 안에서 문자를 작성하면 오류가 발생합니다.

    
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
      <Text>문자는 Text 태그 사이에 작성!!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

13) <ScrollView>
앱 화면을 벗어나는 영역의 경우 ScrollView 엘리먼트로 감싸면 스크롤이 가능해지면서 모든 컨텐츠를 볼 수 있습니다. 다음 코드를 복사 붙여넣기 해보세요!

좀 길어보이지만 같은 코드 복붙을 여러번 한 코드입니다 😉

<import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  return (
		//각 태그들에는 style이라는 속성을 갖습니다.
		//이 속성은 파일 최하단에 작성한 스타일 코드 객체의 키 값을 부여해
    // 엘리먼트들에 스타일을 줄 수 있습니다.
    //이는 JSX문법을 배우고 난 다음 더 자세히 다룹니다.
    <View style={styles.container}>
			{/* //보인 영역을 갖는 엘리먼트 7가 반복적으로 쓰였습니다. */}
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </View>
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </View>
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </View>
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </View>
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </View>
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </View>
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </View>
    </View>
  );
}

//텍스트가 영역을 갖고, 가운데 정렬도 하며, 테두리 스타일을 갖게 끔 하는 코드입니다.
//JSX를 마저 배우고 스타일에 대해 자세히 다루니
//걱정 안해도 좋습니다!
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  textContainer: {
    height:100,
    borderColor:'#000',
    borderWidth:1,
    borderRadius:10,
    margin:10,
  },
  textStyle: {
    textAlign:"center"
  }
});
>


- 14) `<Button>`과 함수
    
    👉 대부분 앱엔, 버튼이 당연히 있죠? 그리고 그 버튼을 누르면 팝업이 뜨기도하고, 다른 페이지로 넘어가기도 하며 이 밖의 다양한 기능들이 실행됩니다.
    
    우리도 그 버튼을 손쉽게 화면에 달 수 있습니다. 다음 코드를 `App.js`에 넣어주세요

import React from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>아래 버튼을 눌러주세요</Text>
        {/* 버튼 onPress 속성에 일반 함수를 연결 할 수 있습니다. */}
        <Button 
          style={styles.buttonStyle} 
          title="버튼입니다 "
          color="#f194ff" 
          onPress={function(){
            Alert.alert('팝업 알람입니다!!')
          }}
        />
        {/* ES6 문법으로 배웠던 화살표 함수로 연결 할 수도 있습니다. */}
        <Button 
            style={styles.buttonStyle} 
            title="버튼입니다 "
            color="#FF0000" 
            onPress={()=>{
              Alert.alert('팝업 알람입니다!!')
            }}
          />
          </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  textContainer: {
    height:100,
    margin:10,
  },
  textStyle: {
    textAlign:"center"
  },
});

- 15) `<TouchableOpacity/>`
    

    💡 Button 엘리먼트는 본인의 영역을 갖습니다. 그렇기 때문에 스타일에도 신경을 써야 하고 ScrollView에서 처럼 카드 형식으로 만든 다음 화면 같은 경우엔 버튼 태그를 사용하기 어렵습니다.
    
    저 영역을 충분히 갖는 텍스트 카드 부분을 눌러야 할 때 말이죠!
    
import React from 'react';
import { StyleSheet, Text, View, ScrollView, TouchableOpacity, Alert } from 'react-native';

export default function App() {
  const customAlert = () => {
    Alert.alert("TouchableOpacity에도 onPress 속성이 있습니다")
  }
  return (
    <ScrollView style={styles.container}>
      <TouchableOpacity style={styles.textContainer} onPress={customAlert}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.textContainer} onPress={customAlert}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.textContainer} onPress={customAlert}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.textContainer} onPress={customAlert}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.textContainer} onPress={customAlert}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.textContainer} onPress={customAlert}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.textContainer} onPress={customAlert}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </TouchableOpacity>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  textContainer: {
    height:100,
    borderColor:'#000',
    borderWidth:1,
    borderRadius:10,
    margin:10,
  },
  textStyle: {
    textAlign:"center"
  }
});

- 16) `<Image>`
    

    👉 앱에 이미지도 넣어봐야겠죠!
    두 가지 방식이 있습니다. `assets` 폴더에 있는 이미지를 가져와서 사용하는 방법과 `(import)`, 
    외부 이미지 링크를 넣어서 사용하는 방식입니다`(uri)`.
    
18) 화면을 꾸며주는 StyleSheet 문법
import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>스파르타 코딩클럽!!</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    //영역을 잡는 속성입니다. 따로 자세히 다룹니다.
    //flex: 1은 전체 화면을 가져간다는 뜻입니다
    flex: 1,
    //영역의 배경 색을 결정합니다
    backgroundColor: '#fff',
    //아래 두 속성은 영역 안의 컨텐츠들의 배치를 결정합니다. 
    //flex를 자세히 다룰때 같이 자세히 다룹니다
    justifyContent:"center",
    alignContent:"center"
  },
  textContainer: {
    //영역의 바깥 공간 이격을 뜻합니다(하단 이미지 참조)
    margin:10,
    //영역 안의 컨텐츠 이격 공간을 뜻합니다(하단 이미지 참조)
    padding: 10,
    //테두리의 구부러짐을 결정합니다. 지금 보면 조금 둥글죠?
    borderRadius:10,
    //테두리의 두께를 결정합니다
    borderWidth:2,
    //테두리 색을 결정합니다
    borderColor:"#000",
    //테구리 스타일을 결정합니다. 실선은 solid 입니다
    borderStyle:"dotted",

  },
  textStyle: {
    //글자 색을 결정합니다. rgb, 값 이름, 색상코드 모두 가능합니다
    color:"red",
    //글자의 크기를 결정합니다
    fontSize:20,
    //글자의 두께를 결정합니다
    fontWeight:"700",
    //가로기준으로 글자의 위치를 결정합니다
    textAlign:"center"
  }
});

👉 `margin`과 `padding`은 다음 이미지들 처럼, 영역의 바깥과 안의 여백을 결정합니다. 그럼 `margin`과 `padding`을 늘려보고 줄여보면서 확인해보세요!



![https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ad15fb70-00ef-4dcd-8bd6-e1fb2c32488e/Untitled.png](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ad15fb70-00ef-4dcd-8bd6-e1fb2c32488e/Untitled.png)

![https://s3-us-west-2.amazonaws.com/secure.notion-static.com/86e8d9d7-03f2-448f-8703-1a4a8e0ea8d3/Untitled.png](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/86e8d9d7-03f2-448f-8703-1a4a8e0ea8d3/Untitled.png)


👉 스타일에 대한 속성과, 속성값은 모든 개발자들이 외우고 있지 않습니다. 그때그때 필요한 속성을 검색하고 값도 찾아 사용합니다. 

그러니 너무 외우려고 하지 말고, 이런게 있구나 그리고 검색하면 되는 구나라고 편하게 마음을 가지시면 됩니다.

-스타일 공식 문서
https://reactnative.dev/docs/style#docsNav
https://reactnative.dev/docs/layout-props

또는 구글에 " react native [필요한 스타일] " 이런식으로 검색해도 많은 레퍼런스를 찾을 수 있습니다.



- 19) Flex
    
   
    👉 앱 화면을 구성할 때 사실 `flex`가 가장 중요하다고 봐도 과언이 아닙니다. 
    영역의 레이아웃을 결정하기 때문입니다!
    
    당부드리고 싶은 말씀은, 지금 이해가 안된다고 해서 너무 자책할 필요없습니다. 위에서 배운 스타일 코드들과 달리, flex는 자주 쓰고, 눈으로 확인하는 연습이 좀 수반되야 손에 익는 문법이기 때문입니다. 따라서 지금은 이해되는대로만 받아들이고, 앞으로 우리가 앱을 만들면서 차차 익숙해질 예정이니 너무 걱정하지 않으셔도 됩니다!
    
    일단 `flex` 부터 `flex`와 같이 사용하는 중요 속성들까지 하나하나 살펴보겠습니다
    

    
    - `flex`
        
      
        👉 영역을 차지하는 속성입니다.
        상대적인 개념이 좀 들어가는데요! 다음 화면을 보겠습니다.
        
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.containerOne}>

      </View>
      <View style={styles.containerTwo}>

      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex:1
  },
  containerOne: {
    flex:1,
    backgroundColor:"red"
  },
  containerTwo:{
    flex:2,
    backgroundColor:"yellow"
  }
});

다시말해 flex는 상대적입니다.

가장 최상위의 container 스타일을 가져가는 View 엘리먼트는 디바이스 전체 화면의 영역을 가져갑니다.

안 쪽의 containerOne 스타일이 부여된 View 엘리먼트는 전체를 3등분한 뒤 1/3을 가져가고 containerTwo는 2/3를 가져갑니다.

즉, 같은 레벨의 엘리먼트들의 flex 합을 각자의 flex 속성값 대로 가져갑니다. 또 하나 예제를 살펴보겠습니다.

0개의 댓글