스파르타 앱개발종합반 2주차-2

thermal·2022년 10월 16일
0

주의) Expo 실행 시 내가 작업 폴더에 들어와있는지 확인하기

JSX 문법 - 앱 화면 만들기

  • App.js : JSX 문법으로 그려져 준비된 화면을 반환
  • JSX : <View> <Text>와 같은 대문자로 시작하는 태그
  • <View> </View>와 같이 닫는 태그로 온전히 화면의 한 영역을 구상하는 것을 엘리먼트라고 부름

App.js 기본 코드

//우리가 리액트, 리액트 네이티브, 엑스포 라이브러리에서 꺼내 사용할 기능들을
//이렇게 앞으로도 상단에 선언한다음 가져다 사용합니다.
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

//App.js는 결국 App 함수를 내보내기 하고 있는 자바스크립트 파일입니다.
//이 함수는 무언가?를 반환하고 있는데 결국 화면을 반환하고 있습니다.
export default function App() {
	//화면을 반환합니다.
	//HTML 태그 같이 생긴 이 문법은 JSX라 불리우며 실제 화면을 그리는 문법입니다,
	//이번 강의에서 자세히 다룹니다

  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>
      <StatusBar style="auto" />
    </View>
  );
}

// styles 변수 이름 답게 화면을 그려주는, 
//더 자세히는 JSX문법을 꾸며주는 내용을 담고 있습니다.
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
  • react와 react-native 도구 2개는 항상 갖춰져있어야 한다
  • export default function App() : 모든 JS 리액트 네이티브 파일은 큰 함수 안에서 코드를 작성함
    export default는 이 파일의 함수를 밖으로 내보내는 키워드
  • return문 안에선 화면을 나타내는 코드를 작성하고, 밖에서는 함수를 사용한다
  • 예) <StatusBar style="auto" />는 와이파이, 시계 등이 있는 상단바 아이콘 색을 결정한다. light는 흰색, dark는 검은색
  • 화면을 그리는 JSX 문법은 태그가 대문자로 시작한다
  • <View style={styles.container}> : 맨 아래서 만든 styles 객체를 가져와 View 태그(화면)에 적용한다

export default function App() {
  return (
    <View style={styles.container}>
      <Text style = {styles.textStyle}>스파르타</Text> //스타일 적용
      <StatusBar style="dark" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  textStyle: {  //스타일 추가
    color:'green'
  }
});
  • Text 태그에 스타일을 입힌 예시
  • styles 객체에 textStyle을 추가했고, 그걸 Text 태그에 적용함

JSX 기본 문법

  1. 모든 태그는 가져와서 사용
    : import { StyleSheet, Text, View } from 'react-native';
    JSX 태그 공식 사용 설명서 여기서 태그 사용방법을 찾을 수 있다
  2. 태그는 항상 닫는 태그와 자체적으로 닫는 태그를 구분해서 사용
    • <View> 영역 <View> : 본인 영역을 가짐
    • <StatusBar style="dark" /> : 본인 스스로 닫는 태그
  3. 모든 엘리먼트는 감싸는 최상위 엘리먼트(태그)가 있어야 함
    : <Text><StatusBar>를 감싸는 <View> </View>가 가 최상위 엘리먼트
  4. return에 의해 렌더링 될 땐 항상 소괄호()로 감싸져야 함
  5. JSX 밖의 주석 : // 주석
    JSX 안의 주석 : {/* 주석 */}
//JSX밖에서의 주석
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
//JSX밖에서의 주석
export default function App() {
	//JSX밖에서의 주석
  return (
		//JSX 밖에서의 주석
    <View style={styles.container}>
			{/*
				JSX 문법 안에서의 주석
			*/}
      <Text>Open up App.js to start working on your app!</Text>
      <StatusBar style="auto" />
    </View>
  );
}

//JSX밖에서의 주석
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});


앱 화면 만들기

View 태그

  • 화면의 영역(레이아웃)을 잡아주는 엘리먼트
  • 현재 App.js에서 View는 화면 전체 영역을 가진다
  • View 태그로 아래와 같이 화면을 마음대로 분할 가능
import { StatusBar } from 'expo-status-bar';
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"
  }
});
  • 같은 위치(레벨)에 View 태그가 2개 있고 각각 다른 색을 입힌 것을 볼 수 있다
  • backgroundColor는 View 태그 바탕색을 결정

Text 태그

  • 화면에 나타낼 문자 작성 시 항상 Text 태그 안에서 작성
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',
  },
});

ScrollView 태그

  • 앱 화면을 벗어나는 영역은 ScrollView 엘리먼트로 감싸면 스크롤이 가능해지면서 모든 컨텐츠를 볼 수 있다
  • 그냥 View로 감싸면 스크롤 불가능
import React from 'react';
import { StyleSheet, Text, View, ScrollView } from 'react-native'; // ScrollView 가져와서 쓴다

export default function App() {
  return (
    <ScrollView style={styles.container}>  
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </View>
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>영역을 충분히 갖는 텍스트 입니다!</Text>
      </View>
    </ScrollView>
  );
}
// 길어서 줄였음..

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

SafeAreaView 태그

  • 폰 기종 차이로 인해 화면이 상태바에 가려져서 일부가 보이지 않는 현상 방지
  • 상태바 영역을 제외한 영역만을 화면으로 쓰는 태그

Button 태그

  • 버튼 생성 태그
  • 안에서 닫힌다
import React from 'react';
import { StyleSheet, Text, View, Button, Alert, SafeAreaView } from 'react-native';

export default function App() {
  return (
    <SafeAreaView 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>
    </SafeAreaView>
  );
}

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

    • style : 스타일 적용. style = {적용할스타일객체}
    • title : 버튼 안의 글자
    • color : 버튼 안의 글자 색
    • onPress : 눌렀을 때의 액션(실행될 함수를 여기 작성). onPress={함수}
  • Alert.alert('팝업 알림') : 팝업 구현 함수

  • 버튼 설명서
    https://reactnative.dev/docs/button

  • 팝업 알람(Alert) 설명서
    https://reactnative.dev/docs/alert#docsNav

onPress에 연결한 함수를 JSX 밖에서 구현 후 연결

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

export default function App() {
  //화살표 함수 형식으로 함수를 정의하고
  //jSX문법 안에서 사용할 수 있습니다
  const customAlert = () => {
    Alert.alert("JSX 밖에서 함수 구현 가능!")
  }
  return (
    <View style={styles.container}>
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>아래 버튼을 눌러주세요</Text>
        {/* onPress에 밖에서 구현한 함수 이름을 고대로 넣을 수도 있고*/}
        <Button 
          style={styles.buttonStyle} 
          title="버튼입니다 "
          color="#f194ff" 
          onPress={customAlert}
        />
        {/* onPress를 누르면 속성에 바로 구현해 놓은 함수 안에 customALert함수를 두고 실행할 수 있게도 가능합니다 */}
        <Button 
            style={styles.buttonStyle} 
            title="버튼입니다 "
            color="#FF0000" 
            onPress={() => {customAlert()}}
          />
          </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  textContainer: {
    height:100,
    margin:10,
  },
  textStyle: {
    textAlign:"center"
  },
});
  • return 밖에서 정의한 customAlert() 함수를 return 안의 Button 태그 onPress 속성에 적용함
  • onPress={customAlert} : onPress에 함수를 바로 바인딩하려면 ()는 붙이면 안됨
  • onPress={() => {customAlert()}} : 바깥에 함수를 만들고 그 안에 함수를 부를 경우는 () 붙임

TouchableOpacity 태그

  • Button 태그와 같은 기능이지만 스타일을 입히기 더 수월하다
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"
  }
});

0개의 댓글