[왕초보] 나만의 수익성 앱, 앱개발 종합반 2주차

2022. 8. 16. 18:17배울수록 연봉은 늘어간다./앱개발

728x90

2-1 리액트 네이티브 앱 개발&expo

  • 리액트 네이티브 = 리액트 +네이티브
  • expo  : 안드로이드 , ios 코드를 하나도 몰라도 자바스크립트로만 앱 개발이 가능한 도구

개발환경 만들기

1. 앱 설치

  • IOS 클라이언트 앱 다운 (링크)
  • 안드로이드 클라이언트 앱 다운 (링크)

2. 터미널 실행 (cmd)

yarn 설치 

  • npm install -g yarn
  • 맥 사용자는 sudo npm install -g yarn

yarn 설치

  • yarn 설치 후 제대로 깔렸는지 버전 확인하기
  • yarn -v 실행
  • 화면 정리 명령어
  • 윈도우 사용자 : cls
  • 맥 사용자 : clear

yarn 버전

 

expo 설치

  • 윈도우 사용자 : npm install -g expo-cli
  • 맥 사용자 : sudo npm install -g expo-cli

  • expo 설치 후 제대로 깔렸는지 버전 확인하기
  • expo --version 실행

expo --version

3.'배포' 계정 세팅

 

  • expo 회원 가입하기
 

Sign Up — Expo

Create an account for Expo here.

expo.dev

 

  • cmd에서 expo 계정 연결하기
  • 터미널에서 expo login 실행
  • 가입했던 이메일 , 비밀번호를 입력하세요.

 

4. 바탕화면에 폴더를 하나 만들어 줍니다. 폴더명은 영어로 해주세요. 

5. vs code 실행

vs code 실핼화면

 

  • 폴더를 연결해 주면 아래와 같은 화면을 보실 수 있습니다.

폴더연결

 

6. expo 프로젝트 생성하기

  • 터미널 창을 엽니다.
  • 단축키 : ctrl + ~ 
  • expo init 프로젝트 폴더명 
  • 선택 화면이 나오는데 'blank'로 실행합니다. (빈 스케치)

 

  • 설치 완료 후 화면입니다.

 

  • 설치 완료 후 expo start를 눌러 핸드폰으로 qr 코드를 실행해 봅니다.

 

  • 설치할 때 나오는 문제점들~~~
 

[스파르타코딩클럽] 앱개발 종합반 - FAQ

본 FAQ 문서에는 앱개발 종합반 강의를 운영하며 쌓인 다양한 질문들에 대한 답변이 담겨있습니다. 그러나, 튜티 여러분의 PC환경은 모두 다르기에 현실적으로 본 문서가 100% 답변이 되지는 못합

www.notion.so


2-2 jsx 문법

  • vs code를 실행합니다.
  • 디렉터리를 확인합니다.
  • 터미널에 expo start를 실행합니다.

1.APP.js 

  • 기본 세팅 화면

 

  • 리턴 밖은 함수
  • 리턴 안은 앱 화면에 보이는 것들

 

  • <text> 부분을 바꾸어서 글자가 바뀌는지 확인을 해봅니다.

 

  • <text> 컬러 바꾸기
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}>
      <Text style={styles.textStyle}>안녕하세요!!</Text>
      <StatusBar style="auto" />
    </View>
  );
}

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

 

 

  • 중괄호 안에 들어있는 태그를 사용할 수 있는 공식 문서 사이트입니다.

 

ActivityIndicator - Expo Documentation

Expo is an open-source platform for making universal native apps for Android, iOS, and the web with JavaScript and React.

docs.expo.dev

 

  • 주석처리
  • //jsx 밖에서의 주석
  • {/*jsx안에서의 주석*/}
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
//jsx 밖에서의 주석
  return (
    <View style={styles.container}>
      <Text style={styles.textStyle}>안녕하세요!!</Text> {/* jsx 안에서의 주석 */}
      <StatusBar style="auto" /> 
    </View>
  );
}

 

  • 실수를 줄이기 위한 확장팩 설치
  • Material Icon Theme
  • [Deprecated] Bracket Pair Colorizer 2 (이건 자동으로 설치가 되어 있는 거 같아요)

 


2-3 화면 구성 (태그의 종류)

1. 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. 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',
  },
});

text 결과

3. ScrollView

  • 많은 데이터를 보기 위한 용도
import React from 'react';
import { StyleSheet, Text, View, ScrollView } from 'react-native';

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>
      <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>
    </ScrollView>
  );
}

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

ScrollView 결과

 

4. SafeAreaView

  • View 태그를 최상위로 놓았을 때 아이폰처럼 생긴 경우 글자가 잘리는 경우가 있을 때 사용합니다.
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"
  },
});

5.TouchableOpacity

  • 스크롤 기능도 있으면서 버튼을 눌렀을 때  액션 기능이 있습니다.
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"
  }
});

 

 

6.Image

  • 외부에 있는 이미지 주소를 입력합니다.
import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
//이렇게 상단에 가져와 사용할 이미지를 불러옵니다
import favicon from "./assets/favicon.png"

export default function App() {
  return (
    <View style={styles.container}>
			{/*이미지 태그 soruce 부분에 가져온 미지 이름을 넣습니다 */}
      <Image 
        source={{uri:'https://images.unsplash.com/photo-1424819827928-55f0c8497861?fit=crop&w=600&h=600%27'}}
				// 사용설명서에 나와 있는 resizeMode 속성 값을 그대로 넣어 적용합니다
        resizeMode={"cover"}
        style={styles.imageStyle}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    //혹시 미리 궁금하신 분들을 위해 언급하자면,
    //justifyContent와 alignContent는 영역 안에 있는 콘텐츠들을 정렬합니다
    justifyContent:"center",
    alignContent:"center"
  },
  imageStyle: {
    width:"100%",
    height:"100%",
    alignItems:"center",
    justifyContent:"center"
  }
});

이미지 결과 화면

7. 자주 사용하는 스타일 속성

  • textContainer 이 부분의 속성을 바꾸면서 화면이 어떻게 바뀌는지 확인합니다. 
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"
  }
});

 

8.flex

  • 합의 개념과 상대적인 개념이 있습니다.
  • 영역을 100%로 보고 몇 퍼센트를 가져갈 거냐를 숫자로 표현한 것입니다.
  • flex영역 안에서 콘텐츠의 위치를 결정하는 건 flexDirection 으로 방향을 결정합니다.
  • justifyContent , alignItems 영역 안에  위치 왼쪽이냐 오른쪽이냐 가운데냐의 위치를 결정합니다.
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 style={styles.innerOne}>

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

        </View>

      </View>
    </View>
  );
}

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


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 style={styles.innerOne}>

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

        </View>

      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex:1
  },
  containerOne: {
    flex:1,
    backgroundColor:"red"
  },
  containerTwo:{
    flex:2,
    flexDirection:"row",
    backgroundColor:"yellow"
  },
  innerOne: {
    flex:1,
    backgroundColor:"blue"
  },
  innerTwo: {
    flex:4,
    backgroundColor:"orange"
  }
});

flexDirection

 


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 style={styles.innerOne}>
         
        </View>
        <View style={styles.innerTwo}>
          <Text>!!컨텐츠!!</Text>
        </View>

      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex:1
  },
  containerOne: {
    flex:1,
    backgroundColor:"red"
  },
  containerTwo:{
    flex:2,
    flexDirection:"row",
    backgroundColor:"yellow"
  },
  innerOne: {
    flex:1,
    backgroundColor:"blue"
  },
  innerTwo: {
    flex:4,
    justifyContent:"flex-start",
    backgroundColor:"orange"
  }
});

justifyContent


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 style={styles.innerOne}>
         
        </View>
        <View style={styles.innerTwo}>
          <View style={styles.content}></View>
        </View>

      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex:1
  },
  containerOne: {
    flex:1,
    backgroundColor:"red"
  },
  containerTwo:{
    flex:2,
    flexDirection:"row",
    backgroundColor:"yellow"
  },
  innerOne: {
    flex:1,
    backgroundColor:"blue"
  },
  innerTwo: {
    flex:4,
    backgroundColor:"orange",
    alignItems:"flex-end"
  },
  content: {
    width:50,
    height:50,
    backgroundColor:"#000"
  }
});

alignItems


2-4. 메인 화면 만들기

1. 골격

import React from 'react';
import main from './assets/main.png';
import { StyleSheet, Text, View, Image, TouchableOpacity, ScrollView} from 'react-native';
  • import { StyleSheet, Text, View, Image, TouchableOpacity, ScrollView} from 'react-native';
  • 구현하고자 하는 태그를 사용하는 공간입니다.

export default function App() {
  return ()

}

const styles = StyleSheet.create({})
  • 리턴 밖은 함수 입력
  • 리턴 안은 앱에서 보이는 화면을 입력
  • const styles = StyleSheet.create({}) 앱에서 보여지는 모습을 세밀하게 표현

2. 코드 분석

"나만의 꿀팁" 글자 넣기

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View,SafeAreaView } from 'react-native';

export default function App() {

  return (
    <SafeAreaView style={styles.container}>
     <Text style={styles.title}>나만의 꿀팁</Text>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
    container: {
      //앱의 배경 색
      backgroundColor: '#fff',
    },
    title: {
      //폰트 사이즈
      fontSize: 20,   
      //폰트 두께
      fontWeight: '700',
      //위 공간으로 부터 이격
      marginTop:50,
        //왼쪽 공간으로 부터 이격'
      marginLeft:20
    },
  });

결과물

 


이미지 넣기

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { Image,StyleSheet, Text, View,SafeAreaView } from 'react-native';

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
export default function App() {

  return (
    <SafeAreaView style={styles.container}>
     <Text style={styles.title}>나만의 꿀팁</Text>
     <Image style={styles.mainImage} source={{uri:main}}/>
    </SafeAreaView>
    
  );
}

const styles = StyleSheet.create({
    container: {
      //앱의 배경 색
      backgroundColor: '#fff',
    },
    title: {
      //폰트 사이즈
      fontSize: 20,   
      //폰트 두께
      fontWeight: '700',
      //위 공간으로 부터 이격
      marginTop:50,
        //왼쪽 공간으로 부터 이격'
      marginLeft:20
    },
    mainImage: {
      //컨텐츠의 넓이 값
      width:'90%',
      //컨텐츠의 높이 값
      height:200,
      //컨텐츠의 모서리 구부리기
      borderRadius:10,
      marginTop:20,
      //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
      //각 속성의 값들은 공식문서에 고대로~ 나와 있음
      alignSelf:"center"
    },
  });

 

추가된 코드

  • const : 변하지 않는다.
<Image style={styles.mainImage} source={{uri:main}}/>
  • 이미지 컴포넌트에 이미지를 지정해주기 위해서 source라는 속성을 명시해줘야합니다.
옵션
 mainImage: {
      //컨텐츠의 넓이 값
      width:'90%',
      //컨텐츠의 높이 값
      height:200,
      //컨텐츠의 모서리 구부리기
      borderRadius:10,
      marginTop:20,
      //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
      //각 속성의 값들은 공식문서에 고대로~ 나와 있음
      alignSelf:"center"
    },
 

alignSelf 사용법

 

align-self - CSS: Cascading Style Sheets | MDN

The align-self CSS property overrides a grid or flex item's align-items value. In Grid, it aligns the item inside the grid area. In Flexbox, it aligns the item on the cross axis.

developer.mozilla.org

결과물

 


글자 만들기

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { scrollView,Image,StyleSheet, Text, View,SafeAreaView, ScrollView } from 'react-native';

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
export default function App() {

  return (
    <SafeAreaView style={styles.container}>
     <Text style={styles.title}>나만의 꿀팁</Text>
     <Image style={styles.mainImage} source={{uri:main}}/>
    
    

    <ScrollView style={styles.scrollView}>
        <Text style={styles.text}> 안녕하세요</Text>
    


      </ScrollView>
      </SafeAreaView>
  );
}

const styles = StyleSheet.create({
    container: {
      //앱의 배경 색
      backgroundColor: '#fff',
    },
    title: {
      //폰트 사이즈
      fontSize: 20,   
      //폰트 두께
      fontWeight: '700',
      //위 공간으로 부터 이격
      marginTop:50,
        //왼쪽 공간으로 부터 이격'
      marginLeft:20
    },
    mainImage: {
      //컨텐츠의 넓이 값
      width:'90%',
      //컨텐츠의 높이 값
      height:200,
      //컨텐츠의 모서리 구부리기
      borderRadius:10,
      marginTop:20,
      //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
      //각 속성의 값들은 공식문서에 고대로~ 나와 있음
      alignSelf:"center"
    },







  });

추가된 코드

<ScrollView style={styles.scrollView}>
<Text style={styles.text}>안녕하세요 </Text>

 </ScrollView>
  • ScrollView : 구현하려는 내용의 높이가 실제 화면의 높이보다 클 때 화면을 스크롤할 수 있도록 하기 위해 사용한다. ScrollView를 이용하여 내용을 감싸주면 화면의 높이보다 내용물이 커질 때 자동으로 스크롤이 가능하도록 된다.

옵션 (margin :바깥쪽 영역 설정합니다.)

 

middleContainer:{

marginTop:20,

marginLeft:10,

height:60

},

 

margin-top - CSS: Cascading Style Sheets | MDN

margin-top CSS 속성은 요소의 위쪽에 바깥 여백 영역margin area을 설정합니다. 양수 값은 인접 요소와 거리를 넓히고, 음수 값은 더 좁힙니다.

developer.mozilla.org

 

화살표가 친 부분에 코딩을 하게 되면 글자의 배열이 가로로 변하게 된다.

horizontal indicatorStyle={"white"}
  • horizontal  : 가로로 배열해주세요
  • indicatorStyle : 스크롤의 색상을 변경해주세요. = {" 옵션" : black , white 중 선택 }
01

버튼에 영혼을 넣어 봅시다!

import React from 'react';
import { Image, SafeAreaView, ScrollView, StyleSheet, Text } from 'react-native';

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
export default function App() {

  return (
    <SafeAreaView style={styles.container}>
     <Text style={styles.title}>나만의 꿀팁</Text>
     <Image style={styles.mainImage} source={{uri:main}}/>
    
    <ScrollView style={styles.middleContainer} horizontal indicatorStyle={"white"}>
        <Text style={styles.middleButtonText}> 생활</Text>
        <Text style={styles.middleButtonText}> 재테크</Text>
        <Text style={styles.middleButtonText}> 반려견</Text>
        <Text style={styles.middleButtonText}> 꿀팁 찜</Text>


      </ScrollView>
      </SafeAreaView>
  );
}

const styles = StyleSheet.create({
    container: {
      //앱의 배경 색
      backgroundColor: '#fff',
    },
    title: {
      //폰트 사이즈
      fontSize: 20,   
      //폰트 두께
      fontWeight: '700',
      //위 공간으로 부터 이격
      marginTop:50,
        //왼쪽 공간으로 부터 이격'
      marginLeft:20
    },
    mainImage: {
      //컨텐츠의 넓이 값
      width:'90%',
      //컨텐츠의 높이 값
      height:200,
      //컨텐츠의 모서리 구부리기
      borderRadius:10,
      marginTop:20,
      //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
      //각 속성의 값들은 공식문서에 고대로~ 나와 있음
      alignSelf:"center"
    },
    middleButtonText: {
      color:"black",
      fontWeight:"100",
      //텍스트의 현재 위치에서의 정렬 
      textAlign:"center"
    },





  });

추가된 코드

 middleButtonText: {
      color:"black",
      fontWeight:"100",
      //텍스트의 현재 위치에서의 정렬 
      textAlign:"center"
    },
  • fontWeight : 글씨 두께를 지정합니다. 'normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'
  • textAlign : 'auto', 'left', 'right', 'center', 'justify' => 현제 가로로 지정되어 있기 때문에 움직임이 없습니다.

글자에 박스 넣기

import React from 'react';
import {TouchableOpacity, Image, SafeAreaView, ScrollView, StyleSheet, Text } from 'react-native';

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
export default function App() {

  return (
    <SafeAreaView style={styles.container}>
     <Text style={styles.title}>나만의 꿀팁</Text>
     <Image style={styles.mainImage} source={{uri:main}}/>
    
    <ScrollView style={styles.middleContainer} horizontal indicatorStyle={"white"}>
    <TouchableOpacity style={styles.middleButton01}><Text style={styles.middleButtonText}> 생활</Text></TouchableOpacity>
        <Text style={styles.middleButtonText}> 재테크</Text>
        <Text style={styles.middleButtonText}> 반려견</Text>
        <Text style={styles.middleButtonText}> 꿀팁 찜</Text>

    
      </ScrollView>
      </SafeAreaView>
  );
}

const styles = StyleSheet.create({
    container: {
      //앱의 배경 색
      backgroundColor: '#fff',
    },
    title: {
      //폰트 사이즈
      fontSize: 20,   
      //폰트 두께
      fontWeight: '700',
      //위 공간으로 부터 이격
      marginTop:50,
        //왼쪽 공간으로 부터 이격'
      marginLeft:20
    },
    mainImage: {
      //컨텐츠의 넓이 값
      width:'90%',
      //컨텐츠의 높이 값
      height:200,
      //컨텐츠의 모서리 구부리기
      borderRadius:10,
      marginTop:20,
      //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
      //각 속성의 값들은 공식문서에 고대로~ 나와 있음
      alignSelf:"center"
    },
    middleButtonText: {
      color:"black",
      fontWeight:"900",
      //텍스트의 현재 위치에서의 정렬 
      textAlign:"justify"
    },
    middleContainer:{
      marginTop:20,
      marginLeft:10,
      height:60
    },
    middleButton01: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#fdc453",
      borderColor:"deeppink",
      borderRadius:15,
      margin:7
    },




  });
추가된 코드
<TouchableOpacity style={styles.middleButton01}>
<Text style={styles.middleButtonText}> 생활 </Text>
</TouchableOpacity>
  • 글자를 터치할 때 효과를 주기 위해 사용합니다.

옵션

middleButton01: {
      width:100, // 너비
      height:50, //높이
      padding:15,
      backgroundColor:"#fdc453",
      borderColor:"deeppink",
      borderRadius:15, // 박스의 모양을 바꿔줍니다.
      margin:7
    },
 
padding에 관련된 공식 문서 확인
 

margin-top - CSS: Cascading Style Sheets | MDN

margin-top CSS 속성은 요소의 위쪽에 바깥 여백 영역margin area을 설정합니다. 양수 값은 인접 요소와 거리를 넓히고, 음수 값은 더 좁힙니다.

developer.mozilla.org

 
 

컬러에 관련된 공식 문서 확인

 

#fdc453 - Google 검색

... marginLeft:10, height:60 }, middleButton01: { width:100, height:50, padding:15, backgroundColor:"#fdc453", borderColor:"deeppink", borderRadius:15, ...

www.google.com

 

borderRadius에 관련된 공식 문서 확인

 

border-radius - CSS: Cascading Style Sheets | MDN

CSS border-radius 속성은 요소 테두리 경계의 꼭짓점을 둥글게 만듭니다. 하나의 값을 사용해 원형 꼭짓점을, 두 개의 값을 사용해 타원형 꼭짓점을 적용할 수 있습니다.

developer.mozilla.org

 

margin에 관련된 공식 문서 확인

 

 

margin - CSS: Cascading Style Sheets | MDN

margin CSS 속성은 요소의 네 방향 바깥 여백 영역을 설정합니다. margin-top, margin-right, margin-bottom, margin-left의 단축 속성입니다.

developer.mozilla.org

 

영역표시!!
 

결과물

 


카드 형태 만들기 1-1

import React from 'react';
import {View, TouchableOpacity, Image, SafeAreaView, ScrollView, StyleSheet, Text } from 'react-native';

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
export default function App() {

  return (
    <SafeAreaView style={styles.container}>
     <Text style={styles.title}>나만의 꿀팁</Text>
     <Image style={styles.mainImage} source={{uri:main}}/>
    
    <ScrollView style={styles.middleContainer} horizontal indicatorStyle={"white"}>
    <TouchableOpacity style={styles.middleButton01}><Text style={styles.middleButtonText}> 생활</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton02}><Text style={styles.middleButtonText}> 재테크</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton03}><Text style={styles.middleButtonText}> 반려견</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton04}><Text style={styles.middleButtonText}> 꿀팁 찜</Text></TouchableOpacity>
    </ScrollView>
    

    <View style={styles.cardContainer}>
    <View style={styles.card}>
    <Image style={styles.cardImage} source={{uri:"https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fpizza.png?alt=media&token=1a099927-d818-45d4-b48a-7906fd0d2ad3"}}/>
      </View>
    </View>
      </SafeAreaView>
  

  );
}

const styles = StyleSheet.create({
    container: {
      //앱의 배경 색
      backgroundColor: '#fff',
    },
    title: {
      //폰트 사이즈
      fontSize: 20,   
      //폰트 두께
      fontWeight: '700',
      //위 공간으로 부터 이격
      marginTop:50,
        //왼쪽 공간으로 부터 이격'
      marginLeft:20
    },
    mainImage: {
      //컨텐츠의 넓이 값
      width:'90%',
      //컨텐츠의 높이 값
      height:200,
      //컨텐츠의 모서리 구부리기
      borderRadius:10,
      marginTop:20,
      //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
      //각 속성의 값들은 공식문서에 고대로~ 나와 있음
      alignSelf:"center"
    },
    middleButtonText: {
      color:"black",
      fontWeight:"900",
      //텍스트의 현재 위치에서의 정렬 
      textAlign:"justify"
    },
    middleContainer:{
      marginTop:20,
      marginLeft:10,
      height:60
    },
    middleButton01: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#fdc453",
      borderColor:"deeppink",
      borderRadius:15,
      margin:7,
    },
    middleButton02: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#fe8d6f",
      borderRadius:15,
      margin:7
    },
    middleButton03: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#9adbc5",
      borderRadius:15,
      margin:7
    },
    middleButton04: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#f886a8",
      borderRadius:15,
      margin:7
    },
    cardContainer: {
      marginTop:10,
      marginLeft:10
    },
    card:{
      flex:1,
      //컨텐츠들을 가로로 나열
      //세로로 나열은 column <- 디폴트 값임 
      flexDirection:"row",
      margin:10,
      borderBottomWidth:0.5,
      borderBottomColor:"#eee",
      paddingBottom:10
   },
      cardImage: {
        flex:1,
        width:100,
        height:100,
        borderRadius:10,
      },


  });

추가된 코드

<View style={styles.cardContainer}>

 

옵션

cardContainer: { marginTop:10, marginLeft:10

},

 

마진으로 영역표시를 해줍니다. (위 그림 참조)

 

추가된 코드

<View style={styles.card}>

 

옵션

card:{ flex:1,

//콘텐츠들을 가로로 나열

//세로로 나열은 column <- 디폴트 값임

flexDirection:"row",

margin:10,

borderBottomWidth:0.5,

borderBottomColor:"#eee",

paddingBottom:10

},

 

flex-direction와 관련된 공식문서

 

flex-direction - CSS: Cascading Style Sheets | MDN

flex-direction CSS 속성은 플렉스 컨테이너 내의 아이템을 배치할 때 사용할 주축 및 방향(정방향, 역방향)을 지정합니다.

developer.mozilla.org

 

 

border-bottom-width와 관련된 공식문서

 

border-bottom-width - CSS: Cascading Style Sheets | MDN

CSS border-bottom-width 속성은 요소의 아래 테두리 너비를 지정합니다.

developer.mozilla.org

 

 

 

padding-bottom와 관련된 공식문서

 

padding-bottom - CSS: Cascading Style Sheets | MDN

padding-bottom CSS 속성은 요소의 아래쪽에 안쪽 여백 영역을 설정합니다.

developer.mozilla.org

 

추가된 코드

<Image style={styles.cardImage} source={{uri:"https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fpizza.png?alt=media&token=1a099927-d818-45d4-b48a-7906fd0d2ad3"}}/>
      </View>
 
옵션
 cardImage: {
        flex:1,
        width:100,
        height:100,
        borderRadius:10,
      },
결과물 1-1

카드 형태 만들기 1-2

import React from 'react';
import {View, TouchableOpacity, Image, SafeAreaView, ScrollView, StyleSheet, Text } from 'react-native';

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
export default function App() {

  return (
    <ScrollView style={styles.container}>
     <Text style={styles.title}>나만의 꿀팁</Text>
     <Image style={styles.mainImage} source={{uri:main}}/>
    
    <ScrollView style={styles.middleContainer} horizontal indicatorStyle={"white"}>
    <TouchableOpacity style={styles.middleButton01}><Text style={styles.middleButtonText}> 생활</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton02}><Text style={styles.middleButtonText}> 재테크</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton03}><Text style={styles.middleButtonText}> 반려견</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton04}><Text style={styles.middleButtonText}> 꿀팁 찜</Text></TouchableOpacity>
    </ScrollView>
    

    <View style={styles.cardContainer}>
    <View style={styles.card}>
    <Image style={styles.cardImage} source={{uri:"https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fpizza.png?alt=media&token=1a099927-d818-45d4-b48a-7906fd0d2ad3"}}/>
    <View style={styles.cardText}>
      <Text style={styles.cardTitle}>먹다 남은 피자를 촉촉하게!</Text>

    </View>
     </View>
      </View>
      </ScrollView>
  

  );
}

const styles = StyleSheet.create({
    container: {
      //앱의 배경 색
      backgroundColor: '#fff',
    },
    title: {
      //폰트 사이즈
      fontSize: 20,   
      //폰트 두께
      fontWeight: '700',
      //위 공간으로 부터 이격
      marginTop:50,
        //왼쪽 공간으로 부터 이격'
      marginLeft:20
    },
    mainImage: {
      //컨텐츠의 넓이 값
      width:'90%',
      //컨텐츠의 높이 값
      height:200,
      //컨텐츠의 모서리 구부리기
      borderRadius:10,
      marginTop:20,
      //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
      //각 속성의 값들은 공식문서에 고대로~ 나와 있음
      alignSelf:"center"
    },
    middleButtonText: {
      color:"black",
      fontWeight:"900",
      //텍스트의 현재 위치에서의 정렬 
      textAlign:"justify"
    },
    middleContainer:{
      marginTop:20,
      marginLeft:10,
      height:60
    },
    middleButton01: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#fdc453",
      borderColor:"deeppink",
      borderRadius:15,
      margin:7,
    },
    middleButton02: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#fe8d6f",
      borderRadius:15,
      margin:7
    },
    middleButton03: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#9adbc5",
      borderRadius:15,
      margin:7
    },
    middleButton04: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#f886a8",
      borderRadius:15,
      margin:7
    },
    cardContainer: {
      marginTop:10,
      marginLeft:10
    },
    card:{
      flex:1,
      //컨텐츠들을 가로로 나열
      //세로로 나열은 column <- 디폴트 값임 
      flexDirection:"row",
      margin:10,
      borderBottomWidth:0.5,
      borderBottomColor:"#eee",
      paddingBottom:10
   },
      cardImage: {
        flex:1,
        width:100,
        height:100,
        borderRadius:10,
      },
      cardText: {
        flex:2,
        flexDirection:"column",
        marginLeft:10,
      },
      cardTitle: {
        fontSize:20,
        fontWeight:"700"
      },


  });
return 다음 부분을 SafeAreaView로 시작을 했는데 Text가 출력이 안되는 것을 확인하고 

추가된 코드

 <Text style={styles.cardTitle}>먹다 남은 피자를 촉촉하게! </Text>
 
 
옵션
 cardTitle: {
        fontSize:20,
        fontWeight:"700"
      },
 
 
fontSize와 관련된 공식문서
 

font-size - CSS: Cascading Style Sheets | MDN

font-size CSS 속성은 폰트의 크기(대문자 "M"의 크기)를 지정합니다. 폰트 크기를 바꾸면 em 과 ex <length> 단위로 계산된 다른 항목들의 크기를 바꿉니다.

developer.mozilla.org

 

 

fontWeight와 관련된 공식문서

 

font-weight - CSS: Cascading Style Sheets | MDN

font-weight CSS 속성은 폰트(font)의 가중치(weight)나 굵기(boldness)를 명시한다. 몇몇 폰트들은 normal 나 bold 일 때만 가능하다.

developer.mozilla.org

 

결과물 1-2

 

 

카드 형태 만들기 1-3

import React from 'react';
import {View, TouchableOpacity, Image, SafeAreaView, ScrollView, StyleSheet, Text } from 'react-native';

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
export default function App() {

  return (
    <ScrollView style={styles.container}>
     <Text style={styles.title}>나만의 꿀팁</Text>
     <Image style={styles.mainImage} source={{uri:main}}/>
    
    <ScrollView style={styles.middleContainer} horizontal indicatorStyle={"white"}>
    <TouchableOpacity style={styles.middleButton01}><Text style={styles.middleButtonText}> 생활</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton02}><Text style={styles.middleButtonText}> 재테크</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton03}><Text style={styles.middleButtonText}> 반려견</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton04}><Text style={styles.middleButtonText}> 꿀팁 찜</Text></TouchableOpacity>
    </ScrollView>
    

    <View style={styles.cardContainer}>
    <View style={styles.card}>
    <Image style={styles.cardImage} source={{uri:"https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fpizza.png?alt=media&token=1a099927-d818-45d4-b48a-7906fd0d2ad3"}}/>
    <View style={styles.cardText}>
      <Text style={styles.cardTitle}>먹다 남은 피자를 촉촉하게!</Text>
      <Text style={styles.cardDesc} numberOfLines={3}>먹다 남은 피자는 수분이 날라가기 때문에 처음처럼 맛있게 먹을 수 없는데요. 이럴 경우 그릇에 물을 받아 전자레인지 안에서 1분 30초에서 2분 정도 함께 돌려주면 촉촉하게 먹을 수 있습니다. 물이 전자레인지 안에서 수증기를 일으키고, 피자에 촉촉함을 더해줍니다.</Text>

    </View>
     </View>
      </View>
      </ScrollView>
  

  );
}

const styles = StyleSheet.create({
    container: {
      //앱의 배경 색
      backgroundColor: '#fff',
    },
    title: {
      //폰트 사이즈
      fontSize: 20,   
      //폰트 두께
      fontWeight: '700',
      //위 공간으로 부터 이격
      marginTop:50,
        //왼쪽 공간으로 부터 이격'
      marginLeft:20
    },
    mainImage: {
      //컨텐츠의 넓이 값
      width:'90%',
      //컨텐츠의 높이 값
      height:200,
      //컨텐츠의 모서리 구부리기
      borderRadius:10,
      marginTop:20,
      //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
      //각 속성의 값들은 공식문서에 고대로~ 나와 있음
      alignSelf:"center"
    },
    middleButtonText: {
      color:"black",
      fontWeight:"900",
      //텍스트의 현재 위치에서의 정렬 
      textAlign:"justify"
    },
    middleContainer:{
      marginTop:20,
      marginLeft:10,
      height:60
    },
    middleButton01: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#fdc453",
      borderColor:"deeppink",
      borderRadius:15,
      margin:7,
    },
    middleButton02: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#fe8d6f",
      borderRadius:15,
      margin:7
    },
    middleButton03: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#9adbc5",
      borderRadius:15,
      margin:7
    },
    middleButton04: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#f886a8",
      borderRadius:15,
      margin:7
    },
    cardContainer: {
      marginTop:10,
      marginLeft:10
    },
    card:{
      flex:1,
      //컨텐츠들을 가로로 나열
      //세로로 나열은 column <- 디폴트 값임 
      flexDirection:"row",
      margin:10,
      borderBottomWidth:0.5,
      borderBottomColor:"#eee",
      paddingBottom:10
   },
      cardImage: {
        flex:1,
        width:100,
        height:100,
        borderRadius:10,
      },
      cardText: {
        flex:2,
        flexDirection:"column",
        marginLeft:10,
      },
      cardTitle: {
        fontSize:20,
        fontWeight:"700"
      },
      cardTitle: {
        fontSize:20,
        fontWeight:"700"
      },
      cardDesc: {
        fontSize:15
      },


  });

 

추가된 코드

<Text style={styles.cardDesc} numberOfLines={3}>먹다 남은 피자는 수분이 날라가기 때문에 처음처럼 맛있게 먹을 수 없는데요. 이럴 경우 그릇에 물을 받아 전자레인지 안에서 1분 30초에서 2분 정도 함께 돌려주면 촉촉하게 먹을 수 있습니다. 물이 전자레인지 안에서 수증기를 일으키고, 피자에 촉촉함을 더해줍니다.</Text>
옵션
cardDesc: {
        fontSize:15
      },
 
  • numberOfLines : 텍스트 생략

결과물 1-3

 

 

카드형태 만들기 1-4

import React from 'react';
import {View, TouchableOpacity, Image, SafeAreaView, ScrollView, StyleSheet, Text } from 'react-native';

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
export default function App() {

  return (
    <ScrollView style={styles.container}>
     <Text style={styles.title}>나만의 꿀팁</Text>
     <Image style={styles.mainImage} source={{uri:main}}/>
    
    <ScrollView style={styles.middleContainer} horizontal indicatorStyle={"white"}>
    <TouchableOpacity style={styles.middleButton01}><Text style={styles.middleButtonText}> 생활</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton02}><Text style={styles.middleButtonText}> 재테크</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton03}><Text style={styles.middleButtonText}> 반려견</Text></TouchableOpacity>
    <TouchableOpacity style={styles.middleButton04}><Text style={styles.middleButtonText}> 꿀팁 찜</Text></TouchableOpacity>
    </ScrollView>
    

    <View style={styles.cardContainer}>
    <View style={styles.card}>
    <Image style={styles.cardImage} source={{uri:"https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fpizza.png?alt=media&token=1a099927-d818-45d4-b48a-7906fd0d2ad3"}}/>
    <View style={styles.cardText}>
      <Text style={styles.cardTitle}>먹다 남은 피자를 촉촉하게!</Text>
      <Text style={styles.cardDesc} numberOfLines={3}>먹다 남은 피자는 수분이 날라가기 때문에 처음처럼 맛있게 먹을 수 없는데요. 이럴 경우 그릇에 물을 받아 전자레인지 안에서 1분 30초에서 2분 정도 함께 돌려주면 촉촉하게 먹을 수 있습니다. 물이 전자레인지 안에서 수증기를 일으키고, 피자에 촉촉함을 더해줍니다.</Text>
      <Text style={styles.cardDate}>2020.09.09</Text>
    </View>
     </View>
      </View>
      </ScrollView>
  

  );
}

const styles = StyleSheet.create({
    container: {
      //앱의 배경 색
      backgroundColor: '#fff',
    },
    title: {
      //폰트 사이즈
      fontSize: 20,   
      //폰트 두께
      fontWeight: '700',
      //위 공간으로 부터 이격
      marginTop:50,
        //왼쪽 공간으로 부터 이격'
      marginLeft:20
    },
    mainImage: {
      //컨텐츠의 넓이 값
      width:'90%',
      //컨텐츠의 높이 값
      height:200,
      //컨텐츠의 모서리 구부리기
      borderRadius:10,
      marginTop:20,
      //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
      //각 속성의 값들은 공식문서에 고대로~ 나와 있음
      alignSelf:"center"
    },
    middleButtonText: {
      color:"black",
      fontWeight:"900",
      //텍스트의 현재 위치에서의 정렬 
      textAlign:"justify"
    },
    middleContainer:{
      marginTop:20,
      marginLeft:10,
      height:60
    },
    middleButton01: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#fdc453",
      borderColor:"deeppink",
      borderRadius:15,
      margin:7,
    },
    middleButton02: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#fe8d6f",
      borderRadius:15,
      margin:7
    },
    middleButton03: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#9adbc5",
      borderRadius:15,
      margin:7
    },
    middleButton04: {
      width:100,
      height:50,
      padding:15,
      backgroundColor:"#f886a8",
      borderRadius:15,
      margin:7
    },
    cardContainer: {
      marginTop:10,
      marginLeft:10
    },
    card:{
      flex:1,
      //컨텐츠들을 가로로 나열
      //세로로 나열은 column <- 디폴트 값임 
      flexDirection:"row",
      margin:10,
      borderBottomWidth:0.5,
      borderBottomColor:"#eee",
      paddingBottom:10
   },
      cardImage: {
        flex:1,
        width:100,
        height:100,
        borderRadius:10,
      },
      cardText: {
        flex:2,
        flexDirection:"column",
        marginLeft:10,
      },
      cardTitle: {
        fontSize:20,
        fontWeight:"700"
      },
      cardTitle: {
        fontSize:20,
        fontWeight:"700"
      },
      cardDesc: {
        fontSize:15
      },
      cardDate: {
        fontSize:10,
        color:"#A6A6A6",
      }


  });

 

추가된 코드

 

<Text style={styles.cardDate}>2020.09.09</Text>
 
옵션
 cardDate: {
        fontSize:10,
        color:"#A6A6A6",
      }
 
결과물&nbsp; 1-4

 


 

모듈 시스템

export default function App()
 
import data from
 
 

딕셔너리와 리스트 복합 구조 (json) 제이슨

 
 

빨간색 줄이 있는 부분을 클릭해서 

마우스 오른쪽 버튼을 눌러 "새 파일"을

만들어 줍니다.

파일명은 data.json입니다.

 

 

 

 

 

 

 


data.json 에 들어 있는 것!

코드를 보면 딕셔너리 형태로 구성되어 있는 것을 확인할  수 있습니다.

{
    "tip":[
        {
            "idx":0,
            "category":"생활",
            "title":"먹다 남은 피자를 촉촉하게!",
            "image":"https://storage.googleapis.com/sparta-image.appspot.com/lecture/pizza.png",
            "desc":"먹다 남은 피자는 수분이 날라가기 때문에 처음처럼 맛있게 먹을 수 없는데요. 이럴 경우 그릇에 물을 받아 전자레인지 안에서 1분 30초에서 2분 정도 함께 돌려주면 촉촉하게 먹을 수 있습니다. 물이 전자레인지 안에서 수증기를 일으키고, 피자에 촉촉함을 더해줍니다.",
            "date":"2020.09.09"
        },
        {
            "idx":1,
            "category":"생활",
            "title":"바나나를 싱싱하게 보관하기",
            "image": "https://storage.googleapis.com/sparta-image.appspot.com/lecture/banana.png",
            "desc":"바나나에 날파리가 꼬이거나 금방 익어버리는 것을 예방하기 위한 방법인데요. 바나나 양쪽 끝을 자른 후, 보관용 케이스나 비닐봉지에 묶어 밀봉합니다. 그리고 냉장고에 넣어주면 되는데요. 하루에 1~2개씩 꺼내서 싱싱하게 먹을 수 있습니다.",
            "date":"2020.09.09"
        },
        {
            "idx":2,
            "category":"생활",
            "title":"셔츠에 묻은 볼펜 자국 없애기",
            "image": "https://storage.googleapis.com/sparta-image.appspot.com/lecture/shirt.png",
            "desc":"셔츠를 자주 입는 사람의 경우, 종종 볼펜 자국이 묻기 마련인데요. 이럴 경우에는 집에 있는 물파스로 가볍게 지울 수 있습니다. 옷 뒷부분을 키친타올로 받쳐 번지는 것을 방지한 후, 볼펜 자국 있는 부분을 물파스로 눌러주고, 키친타올로 닦아냅니다.",
            "date":"2020.09.09"
        },
        {
            "idx":3,
            "category":"재테크",
            "title":"잠자는 내 돈을 찾아라",
            "image": "https://storage.googleapis.com/sparta-image.appspot.com/lecture/money1.png",
            "desc":"‘새는 돈’에는 미처 몰랐던 카드 포인트, 휴면예금이나 환급금도 포함됩니다. 확실히 파악하지 못한 잠자는 돈을 찾아보고 자투리 돈들을 모으는 것도 중요합니다. 케이블방송, 위성방송 서비스를 이용하면서 중복 납부한 요금, 셋톱박스 보증금 등 돌려받지 않은 돈이 있는지 확인 해보세요. 또, 카드 포인트 통합 조회 서비스를 이용해 여러 개의 카드 포인트가 모두 얼마인지 체크해두는 것이 좋습니다. 보험해약 환급금, 휴면 보험금이나 휴면 예금을 찾아보고 돌려받는 일도 요즘에는 어렵지 않습니다.",
            "date":"2020.09.09"
        },
        {
            "idx":4,
            "category":"재테크",
            "title":"할인행사, 한정할인판매 문구의 함정 탈출!",
            "image": "https://storage.googleapis.com/sparta-image.appspot.com/lecture/money2.png",
            "desc":"‘안 사면 100% 할인’이라는 말 들어보셨나요? 견물생심, 좋은 물건을 보면 사고 싶기 마련입니다. 특히 대대적인 ‘할인 행사’ 중인 대형 마트에 갔을 때는 말할 것도 없겠죠. 따라서 생필품을 살 때, 한꺼번에 사서 사용하는 것보다 필요할 때 조금씩 구매하는 편이 좋습니다. 장을 보면서 대형마트에 자주 가다 보면 지금 필요한 것뿐 아니라 앞으로 필요할 것까지 사게 되어 지출이 커지기 때문입니다. 특히 할인 품목을 보면 뜻하지 않은 소비를 하는 경우도 많아진다. 홈쇼핑, 대형마트 등의 ‘할인행사’, ‘한정할인판매’ 등의 문구를 조심하세요. ",
            "date":"2020.09.09"
        },
        {
            "idx":5,
            "category":"생활",
            "title":"방전된 건전지 살리기",
            "image": "https://storage.googleapis.com/sparta-image.appspot.com/lecture/battery.png",
            "desc":"건전지를 다 사용하지 않아도 방전되면, 버리는 경우가 종종 있는데요. 건전지의 무게감이 느껴진다면, 드라이기를 활용해 방전된 건전지를 깨울 수 있습니다. 드라이기 열기를 10초~30초 정도 골고루 가해주면 되는데요. 건전지가 불필요하게 낭비되는 것을 막을 수 있습니다.",
            "date":"2020.09.09"
        },
        {
            "idx":6,
            "category":"반려견",
            "title":"반려견에게 배변 교육 시킬 때",
            "image": "https://storage.googleapis.com/sparta-image.appspot.com/lecture/puppy.png",
            "desc":"우선, 배변패드를 순서대로 돌며 간식을 조금씩 떨어뜨려 놓는다. 2단계는 배변패드 앞에서 기다렸다 반려견이 스스로 올라오면 간식을 주어서 보상하고, 3단계는 “화장실 가자”나 “매트” 같은 명령어를 붙여 말한 뒤 배변패드에 올라오면 간식을 주는 것이다. 마지막 단계는 배변패드에 올라간 반려견이 대소변을 본 다음 간식을 줌으로써 이 장소가 즐거운 곳이라는 인식을 심어주는 것이다. 그리고 무엇보다 1, 2회 사용한 배변패드는 바로 갈아줘야 한다.",
            "date":"2020.09.09"
        },
        {
            "idx":7,
            "category":"반려견",
            "title":"반려견이 주인과 떨어지는 것을 무서워 할 때",
            "image": "https://storage.googleapis.com/sparta-image.appspot.com/lecture/puppy2.png",
            "desc":"분리불안교육은 반려견에게 혼자 남는 법을 알려주기 위한 것이 아니라, 보호자가 ‘언제나 너에게 돌아올 거야’라고 알려주는 교육이다. 반려견과 5초 동안 떨어져 있다가 다시 문을 열고 들어가 손 냄새를 맡게 해주는 훈련을 하루 10번씩 7일 동안 반복하는 ‘5,10,7 법칙’을 통해 반려견의 마음을 편안하게 해줄 수 있다.",
            "date":"2020.09.09"
        },
        {
            "idx":8,
            "category":"반려견",
            "title":"반려견을 아이와 함께 키울 때",
            "image": "https://storage.googleapis.com/sparta-image.appspot.com/lecture/puppy3.png",
            "desc":"‘인간의 행복’을 위해 반려동물을 키우는 것에 대해 꾸준히 비판과 우려를 제기해온 그는 특히 ‘아이들의 정서’를 위해 반려견을 키우려 한다는 부모들에게 당부한다. “반려동물을 통해 아이들의 정서가 좋아진다면, 그것은 부모가 나와 생김새와 느낌, 말과 행동이 다른 동물을 아끼는 모습을 보기 때문입니다.” 인간의 뜻에 의해 인간과 함께 살게 된 생명을 좀 더 이해하고 행복하게 살 수 있도록 하는 것은 역시 인간의 노력에 달려 있다.",
            "date":"2020.09.09"
        },
        {
            "idx":9,
            "category":"재테크",
            "title":"렌탈 서비스 금액 비교해보기",
            "image": "https://storage.googleapis.com/sparta-image.appspot.com/lecture/money2.png",
            "desc":"요즘은 정수기, 공기 청정기, 자동차나 장난감 등 다양한 대여서비스가 활발합니다. 사는 것보다 경제적이라고 생각해 렌탈 서비스를 이용하는 분들이 늘어나고 있는데요. 다만, 이런 렌탈 서비스 이용이 하나둘 늘어나다 보면 그 금액은 겉잡을 수 없이 불어나게 됩니다. 특히, 렌탈 서비스는 빌려주는 물건의 관리비용까지 포함된 것이기에 생각만큼 저렴하지 않습니다. 직접 관리하며 사용할 수 있는 물건이 있는지 살펴보고, 렌탈 서비스 항목에서 제외해보세요. 렌탈 비용과 구매 비용, 관리 비용을 여러모로 비교해보고 고민해보는 것이 좋습니다. ",
            "date":"2020.09.09"
        }

    ]
}

 


App.js에 들어 있는 것!

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

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
import data from './data.json';

export default function App() {
  let tip = data.tip;
  let todayWeather = 10 + 17;
  let todayCondition = "흐림"
  //return 구문 밖에서는 슬래시 두개 방식으로 주석
  return (
    /*
      return 구문 안에서는 {슬래시 + * 방식으로 주석
    */
    <ScrollView style={styles.container}>
      <Text style={styles.title}>나만의 꿀팁</Text>
      <Text style={styles.weather}>오늘의 날씨: {todayWeather + '°C ' + todayCondition} </Text>
      <Image style={styles.mainImage} source={{uri:main}}/>
      <ScrollView style={styles.middleContainer} horizontal indicatorStyle={"white"}>
        <TouchableOpacity style={styles.middleButton01}><Text style={styles.middleButtonText}>생활</Text></TouchableOpacity>
        <TouchableOpacity style={styles.middleButton02}><Text style={styles.middleButtonText}>재테크</Text></TouchableOpacity>
        <TouchableOpacity style={styles.middleButton03}><Text style={styles.middleButtonText}>반려견</Text></TouchableOpacity>
        <TouchableOpacity style={styles.middleButton04}><Text style={styles.middleButtonText}>꿀팁 찜</Text></TouchableOpacity>
      </ScrollView>
      <View style={styles.cardContainer}>
        {/* 하나의 카드 영역을 나타내는 View */}
        { 
          tip.map((content,i)=>{
            return (<View style={styles.card} key={i}>
              <Image style={styles.cardImage} source={{uri:content.image}}/>
              <View style={styles.cardText}>
                <Text style={styles.cardTitle} numberOfLines={1}>{content.title}</Text>
                <Text style={styles.cardDesc} numberOfLines={3}>{content.desc}</Text>
                <Text style={styles.cardDate}>{content.date}</Text>
              </View>
            </View>)
          })
         }
        
      </View>
   
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    //앱의 배경 색
    backgroundColor: '#fff',
  },
  title: {
    //폰트 사이즈
    fontSize: 20,
    //폰트 두께
    fontWeight: '700',
    //위 공간으로 부터 이격
    marginTop:50,
    //왼쪽 공간으로 부터 이격
    marginLeft:20
  },
  weather:{
    alignSelf:"flex-end",
    paddingRight:20
  },
  mainImage: {
    //컨텐츠의 넓이 값
    width:'90%',
    //컨텐츠의 높이 값
    height:200,
    //컨텐츠의 모서리 구부리기
    borderRadius:10,
    marginTop:20,
    //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
    //각 속성의 값들은 공식문서에 고대로~ 나와 있음
    alignSelf:"center"
  },
  middleContainer:{
    marginTop:20,
    marginLeft:10,
    height:60
  },
  middleButton01: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#fdc453",
    borderColor:"deeppink",
    borderRadius:15,
    margin:7
  },
  middleButton02: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#fe8d6f",
    borderRadius:15,
    margin:7
  },
  middleButton03: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#9adbc5",
    borderRadius:15,
    margin:7
  },
  middleButtonText: {
    color:"#fff",
    fontWeight:"700",
    //텍스트의 현재 위치에서의 정렬 
    textAlign:"center"
  },
  middleButton04: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#f886a8",
    borderRadius:15,
    margin:7
  },
  cardContainer: {
    marginTop:10,
    marginLeft:10
  },
  card:{
    flex:1,
    //컨텐츠들을 가로로 나열
    //세로로 나열은 column <- 디폴트 값임 
    flexDirection:"row",
    margin:10,
    borderBottomWidth:0.5,
    borderBottomColor:"#eee",
    paddingBottom:10

  },
  cardImage: {
    flex:1,
    width:100,
    height:100,
    borderRadius:10,
  },
  cardText: {
    flex:2,
    flexDirection:"column",
    marginLeft:10,
  },
  cardTitle: {
    fontSize:20,
    fontWeight:"700"
  },
  cardDesc: {
    fontSize:15
  },
  cardDate: {
    fontSize:10,
    color:"#A6A6A6",
  },


});

결과물

 

추가된 코드 확인!!

import data from './data.json';
 
:data.json 파일을 불러 옵니다.
 
 
 
export default function App() {
let tip = data.tip;
let todayWeather = 10 + 17;
let todayCondition = "흐림"
 
 
 return (
 <Text style={styles.weather}>오늘의 날씨: {todayWeather + '°C ' + todayCondition} </Text>

 

==> API를 사용해서 불러온 값은 아니다. 그냥 틀만 만들어 놓은 거니 참고만 하자!

 

 <View style={styles.cardContainer}>
        {/* 하나의 카드 영역을 나타내는 View */}
        {
          tip.map((content,i)=>{
            return (<View style={styles.card} key={i}>
              <Image style={styles.cardImage} source={{uri:content.image}}/>
              <View style={styles.cardText}>
                <Text style={styles.cardTitle} numberOfLines={1}>{content.title}</Text>
                <Text style={styles.cardDesc} numberOfLines={3}>{content.desc}</Text>
                <Text style={styles.cardDate}>{content.date}</Text>
              </View>
            </View>)
          })
         }
       
      </View>
 
==> 기존에 진행했던 코드와 비교를 해보면 이 부분이 달라진 것을 확인 할 수 있습니다.
 
array.map(callbackFunction(currenValue, index, array), thisArg)

array : data.json에 있는 tip이라는 값을 불러옵니다.

callbackFunction  :  return부터 쓰는 내용

currenValue : 변수

index : 번호 key=[i]

 

공부하면서 몇 번을 돌려 듣고 검색을 해봐도 이해가 잘 안 되는 부분이 i 값인데 왜 저기다가 i를 

쓰고 i 값이 번호를 부여받는지에 대해 지금은 잘 모르겠다.

시간이 지나고 여러 예시를 보면 이해가 되는 날이 오겠지 하며 지나가 본다.

 

  • <View style={styles.card} key={i}>
  • <Image style={styles.cardImage} source={{uri:content.image}}/>
  • <View style={styles.cardText}>
  • <Text style={styles.cardTitle} numberOfLines={1}>{content.title}</Text>
  • <Text style={styles.cardDesc} numberOfLines={3}>{content.desc}</Text>
  • <Text style={styles.cardDate}>{content.date}</Text>
  • </View>
  •  </View>)

=> 기존과 달라진 코드는 "빨간색"으로 표시를 해 두었습니다. 

기존과 달라진 점은 앞전에는 글자를 직접 써서 했다면 지금은 data.json 파일에서 불러온것을

확인할 수 있습니다.

 

arr.map(callback, [thisArg])
  • callback : 새로운 배열의 요소를 생성하는 함수로 파라미터는 다음 세가지입니다.
  • currentValue : 현재 처리하고 있는 요소
  • index : 현재 처리하고 있는 요소의 index값
  • array : 현재 처리하고 있는 원본 배열
  • thisArg(선택항목) : callback 함수 내부에서 사용할 this 레퍼런스

=> 이거는 일단 여기까지만 알고 넘어 가자~


 조건문을 적용해 보자

  • 홀수번에 있는 카드만 색상을 달리해보고 싶다.
  • 삼항 연산자는 리엑트 네이티브로 앱을 만들 때 가장 많이 사용되는 조건문 입니다.

let result = 10 > 2 ? "참" : "거짓"

(기본 모습)
let result = 조건 ? 참일 때 : 거짓 일때

(예제)
let result = 10 == 9 ? true : false  // result <-- false 값 할당  
let result = 10 !== 9 ? true : false // result <-- true 값 할당  
let reuslt = 99 > 10 ? true : false // result <-- true 값 할당

 


let result = 10 > 2 ? "참" : "거짓"

  • 10이 2보다 크다. 그러면 참! 참이면 물음표 뒤에 있는 값이 리절트에 담기게 됩니다.
  • 만약에 거짓이면 
  • 물음표와 이 콜론을 지나서 맨 뒤에 있는 조건이 리절트 변수에 담아지게 됩니다.
  • == : 같다
  • !== : 틀리지??같이 않지? 하며 틀린거에 대해서 물어보는 겁니다.

 

◆ 코드비교

App.js (왼쪽이 기존코드 , 오른쪽이 바뀐 코드) 

1

 

2

 바뀐 코드


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

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
import data from './data.json';

export default function App() {
  let tip = data.tip;
  let todayWeather = 10 + 17;
  let todayCondition = "흐림"
  //return 구문 밖에서는 슬래시 두개 방식으로 주석
  return (
    /*
      return 구문 안에서는 {슬래시 + * 방식으로 주석
    */
    <ScrollView style={styles.container}>
      <Text style={styles.title}>나만의 꿀팁</Text>
      <Text style={styles.weather}>오늘의 날씨: {todayWeather + '°C ' + todayCondition} </Text>
      <Image style={styles.mainImage} source={{uri:main}}/>
      <ScrollView style={styles.middleContainer} horizontal indicatorStyle={"white"}>
        <TouchableOpacity style={styles.middleButton01}><Text style={styles.middleButtonText}>생활</Text></TouchableOpacity>
        <TouchableOpacity style={styles.middleButton02}><Text style={styles.middleButtonText}>재테크</Text></TouchableOpacity>
        <TouchableOpacity style={styles.middleButton03}><Text style={styles.middleButtonText}>반려견</Text></TouchableOpacity>
        <TouchableOpacity style={styles.middleButton04}><Text style={styles.middleButtonText}>꿀팁 찜</Text></TouchableOpacity>
      </ScrollView>
      <View style={styles.cardContainer}>
        {/* 하나의 카드 영역을 나타내는 View */}
        { 
          tip.map((content,i)=>{
            return i % 2 == 0 ? (<View style={styles.cardEven} key={i}>
              <Image style={styles.cardImage} source={{uri:content.image}}/>
              <View style={styles.cardText}>
                <Text style={styles.cardTitle} numberOfLines={1}>{content.title}</Text>
                <Text style={styles.cardDesc} numberOfLines={3}>{content.desc}</Text>
                <Text style={styles.cardDate}>{content.date}</Text>
              </View>
            </View>) : (<View style={styles.cardOdd} key={i}>
                <Image style={styles.cardImage} source={{uri:content.image}}/>
                <View style={styles.cardText}>
                  <Text style={styles.cardTitle} numberOfLines={1}>{content.title}</Text>
                  <Text style={styles.cardDesc} numberOfLines={3}>{content.desc}</Text>
                  <Text style={styles.cardDate}>{content.date}</Text>
                </View>
              </View>)
            
          })
         }
        
      </View>
   
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    //앱의 배경 색
    backgroundColor: '#fff',
  },
  title: {
    //폰트 사이즈
    fontSize: 20,
    //폰트 두께
    fontWeight: '700',
    //위 공간으로 부터 이격
    marginTop:50,
    //왼쪽 공간으로 부터 이격
    marginLeft:20
  },
  weather:{
    alignSelf:"flex-end",
    paddingRight:20
  },
  mainImage: {
    //컨텐츠의 넓이 값
    width:'90%',
    //컨텐츠의 높이 값
    height:200,
    //컨텐츠의 모서리 구부리기
    borderRadius:10,
    marginTop:20,
    //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
    //각 속성의 값들은 공식문서에 고대로~ 나와 있음
    alignSelf:"center"
  },
  middleContainer:{
    marginTop:20,
    marginLeft:10,
    height:60
  },
  middleButton01: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#fdc453",
    borderColor:"deeppink",
    borderRadius:15,
    margin:7
  },
  middleButton02: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#fe8d6f",
    borderRadius:15,
    margin:7
  },
  middleButton03: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#9adbc5",
    borderRadius:15,
    margin:7
  },
  middleButtonText: {
    color:"#fff",
    fontWeight:"700",
    //텍스트의 현재 위치에서의 정렬 
    textAlign:"center"
  },
  middleButton04: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#f886a8",
    borderRadius:15,
    margin:7
  },
  cardContainer: {
    marginTop:10,
    marginLeft:10
  },
  card:{
    flex:1,
    //컨텐츠들을 가로로 나열
    //세로로 나열은 column <- 디폴트 값임 
    flexDirection:"row",
    margin:10,
    borderBottomWidth:0.5,
    borderBottomColor:"#eee",
    paddingBottom:10

  },
  cardImage: {
    flex:1,
    width:100,
    height:100,
    borderRadius:10,
  },
  cardText: {
    flex:2,
    flexDirection:"column",
    marginLeft:10,
  },
  cardTitle: {
    fontSize:20,
    fontWeight:"700"
  },
  cardDesc: {
    fontSize:15
  },
  cardDate: {
    fontSize:10,
    color:"#A6A6A6",
  },
  cardEven:{
    flex:1,
    flexDirection:"row",
    margin:10,
    backgroundColor:"#FFFED7",
    borderRadius:20,
    borderBottomWidth:0.5,
    borderBottomColor:"#eee",
    paddingBottom:10
  },
  cardOdd:{
    flex:1,
    flexDirection:"row",
    margin:10,
    borderBottomWidth:0.5,
    borderBottomColor:"#eee",
    paddingBottom:10
  },

});

  코드 풀이

i % 2 == 0 ?

 

 

  • 연산자
+ 왼쪽의 피연산자에 오른쪽의 피연산자를 더함.
- 왼쪽의 피연산자에서 오른쪽의 피연산자를 뺌.
* 왼쪽의 피연산자에 오른쪽의 피연산자를 곱함.
/ 왼쪽의 피연산자를 오른쪽의 피연산자로 나눔.
% 왼쪽의 피연산자를 오른쪽의 피연산자로 나눈 후, 그 나머지를 반환함.

 

 

  • 문제

#include <stdio.h>

int main()
{
    printf("%d\n", 1 % 3);    // 1: 1을 3으로 나누면 몫은 0 나머지는 1
    printf("%d\n", 2 % 3);    // 2: 2를 3으로 나누면 몫은 0 나머지는 2
    printf("%d\n", 3 % 3);    // 0: 3을 3으로 나누면 몫은 1 나머지는 0
    printf("%d\n", 4 % 3);    // 1: 4를 3으로 나누면 몫은 1 나머지는 1
    printf("%d\n", 5 % 3);    // 2: 5를 3으로 나누면 몫은 1 나머지는 2
    printf("%d\n", 6 % 3);    // 0: 6을 3으로 나누면 몫은 2 나머지는 0

    return 0;
}

나머지 연산 %는 앞의 숫자를 뒤의 숫자로 나눈 뒤 나머지만 구합니다

 


  코드 풀이

<View style={styles.cardEven} key={i}>
<View style={styles.cardOdd} key={i}>
  • odd는 홀수 even은 짝수라는 뜻을 가지고 있습니다.
  •  
 현 프로젝트에서는 조건문은 예시일뿐 사용은 안합니다.

  원복 코드

App.js 


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

const main = 'https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2Fmain.png?alt=media&token=8e5eb78d-19ee-4359-9209-347d125b322c'
import data from './data.json';

export default function App() {
  let tip = data.tip;
  let todayWeather = 10 + 17;
  let todayCondition = "흐림"
  //return 구문 밖에서는 슬래시 두개 방식으로 주석
  return (
    /*
      return 구문 안에서는 {슬래시 + * 방식으로 주석
    */
    <ScrollView style={styles.container}>
      <Text style={styles.title}>나만의 꿀팁</Text>
      <Text style={styles.weather}>오늘의 날씨: {todayWeather + '°C ' + todayCondition} </Text>
      <Image style={styles.mainImage} source={{uri:main}}/>
      <ScrollView style={styles.middleContainer} horizontal indicatorStyle={"white"}>
        <TouchableOpacity style={styles.middleButton01}><Text style={styles.middleButtonText}>생활</Text></TouchableOpacity>
        <TouchableOpacity style={styles.middleButton02}><Text style={styles.middleButtonText}>재테크</Text></TouchableOpacity>
        <TouchableOpacity style={styles.middleButton03}><Text style={styles.middleButtonText}>반려견</Text></TouchableOpacity>
        <TouchableOpacity style={styles.middleButton04}><Text style={styles.middleButtonText}>꿀팁 찜</Text></TouchableOpacity>
      </ScrollView>
      <View style={styles.cardContainer}>
        {/* 하나의 카드 영역을 나타내는 View */}
        { 
          tip.map((content,i)=>{
            return (<View style={styles.card} key={i}>
              <Image style={styles.cardImage} source={{uri:content.image}}/>
              <View style={styles.cardText}>
                <Text style={styles.cardTitle} numberOfLines={1}>{content.title}</Text>
                <Text style={styles.cardDesc} numberOfLines={3}>{content.desc}</Text>
                <Text style={styles.cardDate}>{content.date}</Text>
              </View>
            </View>)
          })
         }
        
      </View>
   
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    //앱의 배경 색
    backgroundColor: '#fff',
  },
  title: {
    //폰트 사이즈
    fontSize: 20,
    //폰트 두께
    fontWeight: '700',
    //위 공간으로 부터 이격
    marginTop:50,
    //왼쪽 공간으로 부터 이격
    marginLeft:20
  },
  weather:{
    alignSelf:"flex-end",
    paddingRight:20
  },
  mainImage: {
    //컨텐츠의 넓이 값
    width:'90%',
    //컨텐츠의 높이 값
    height:200,
    //컨텐츠의 모서리 구부리기
    borderRadius:10,
    marginTop:20,
    //컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
    //각 속성의 값들은 공식문서에 고대로~ 나와 있음
    alignSelf:"center"
  },
  middleContainer:{
    marginTop:20,
    marginLeft:10,
    height:60
  },
  middleButton01: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#fdc453",
    borderColor:"deeppink",
    borderRadius:15,
    margin:7
  },
  middleButton02: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#fe8d6f",
    borderRadius:15,
    margin:7
  },
  middleButton03: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#9adbc5",
    borderRadius:15,
    margin:7
  },
  middleButtonText: {
    color:"#fff",
    fontWeight:"700",
    //텍스트의 현재 위치에서의 정렬 
    textAlign:"center"
  },
  middleButton04: {
    width:100,
    height:50,
    padding:15,
    backgroundColor:"#f886a8",
    borderRadius:15,
    margin:7
  },
  cardContainer: {
    marginTop:10,
    marginLeft:10
  },
  card:{
    flex:1,
    //컨텐츠들을 가로로 나열
    //세로로 나열은 column <- 디폴트 값임 
    flexDirection:"row",
    margin:10,
    borderBottomWidth:0.5,
    borderBottomColor:"#eee",
    paddingBottom:10

  },
  cardImage: {
    flex:1,
    width:100,
    height:100,
    borderRadius:10,
  },
  cardText: {
    flex:2,
    flexDirection:"column",
    marginLeft:10,
  },
  cardTitle: {
    fontSize:20,
    fontWeight:"700"
  },
  cardDesc: {
    fontSize:15
  },
  cardDate: {
    fontSize:10,
    color:"#A6A6A6",
  },


});


설명 페이지 만들기 (AboutPage.js)

1

  • pages 폴더를 만들어주세요.
  • pages 폴더에 MainPage.js와 AboutPage.js 파일을 만들어주세요.

2-1
2-2
2-3

  • App.js 파일 코드 모두 복사한 후, MainPage.js에 붙여넣기 한 다음 함수 이름을 MainPage 로 바꿔주세요.

 

◆ 바뀐코드

MainPage.js


import data from './data.json';

에서

import data from '../data.json';

  • 그리고 MainPage.js의 코드 줄은 위와 같이 변경해주세요. (점 하나만 찍어 주시면 됩니다.)
    1.  

◆ 코드비교

App.js

App.js 있는 코드는 전부 지우고 새로운 코드를 입력해 줍니다.

 

◆ 바뀐 코드

App.js 1-1


import React from 'react'
import MainPage from './pages/MainPage';

export default function App(){
  return (<MainPage/>)
}
  •  

App.js 1-2


import React from 'react'
import MainPage from './pages/MainPage';
import AboutPage from './pages/AboutPage';

export default function App(){
  return (<MainPage/>)
  //return (<AboutPage/>)
}

  • 어바웃 페이지 코드를 추가 했습니다.
  • 핸드폰 화면을 보며 하는게 이해가 빠릅니다.
  • 리턴 코드를 보면 두개이 리턴이 존재하는데 메인페이지를 실행 하고 어바웃 페이지를 주석처리 시키고 있습니다.
  • 현제는 한 페이지만 구현이 가능합니다.
  • 메인 페이지와 어바웃 페이지를 번갈아 가며 실행해 보세요,.
  • 이 방법을 컴포트화 라고 합니다.

◆ 새로운 코드

AboutPage.js


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


export default function AboutPage(){
    const aboutImage = "https://firebasestorage.googleapis.com/v0/b/sparta-image.appspot.com/o/lecture%2FaboutImage.png?alt=media&token=13e1c4f6-b802-4975-9773-e305fc7475c4"
  return (
    <View style={styles.container}>
        <Text style={styles.title}>HI! 스파르타코딩 앱개발 반에 오신것을 환영합니다</Text>
       
        
        <View style={styles.textContainer}>
            <Image style={styles.aboutImage} source={{uri:aboutImage}} resizeMode={"cover"}/>
            <Text style={styles.desc01}>많은 내용을 간결하게 담아내려 노력했습니다!</Text>
            <Text style={styles.desc02}>꼭 완주 하셔서 꼭 여러분것으로 만들어가시길 바랍니다</Text>
            <TouchableOpacity style={styles.button}>
                <Text style={styles.buttonText}>여러분의 인스타계정</Text>
            </TouchableOpacity>
        </View>
    </View>)
}

const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:"#1F266A",
        alignItems:"center"
      
    },
    title: {
        fontSize:30,
        fontWeight:"700",
        color:"#fff",
        paddingLeft:30,
        paddingTop:100,
        paddingRight:30
    },
    textContainer: {
        width:300,
        height:500,
        backgroundColor:"#fff",
        marginTop:50,
        borderRadius:30,
        justifyContent:"center",
        alignItems:"center"
    },
    aboutImage:{
        width:150,
        height:150,
        borderRadius:30
    },
    desc01: {
        textAlign:"center",
        fontSize:20,
        fontWeight:"700",
        paddingLeft:22,
        paddingRight:22

    },
    desc02: {
        textAlign:"center",
        fontSize:15,
        fontWeight:"700",
        padding:22
    },
    button:{
        backgroundColor:"orange",
        padding:20,
        borderRadius:15
    },
    buttonText: {
        color:"#fff",
        fontSize:15,
        fontWeight:"700"
    }
})

◆ 실행 화면

Total : Today : Yesterday :