App.tsx 작성
export default function App(){
// 상수(변경할 수 없는 수)
const str:String = "Hello World"
// return에 두개의 <Text>를 쓰기 위해선 루트태그 사용<SafeAreaView>
return(
<SafeAreaView>
<Text>Hello TSX World</Text>
<Text>{ str }</Text>
</SafeAreaView>
)
}
export default function App(){
const name = '홍길동'
return(
<SafeAreaView>
<Text>Hello Tsx {name}</Text>
</SafeAreaView>
)
}
조건문
export default function App(){
const isLoading = true
// 1. if문을 이용
if(isLoading){ // isLoading == true
return(
<SafeAreaView>
<Text>Loading...</Text>
</SafeAreaView>
)
}else{ // isLoading == false
return(
<SafeAreaView>
<Text>Hello TSX World</Text>
</SafeAreaView>
)
// 2.
return(
<SafeAreaView>
{isLoading && <Text>Loading...</Text>} // isLoading == true
{!isLoading && <Text>Hello Tsx World</Text>} // isLoading == false
</SafeAreaView>
)
// 3.
const child:any = isLoading ? (<Text>Loading...</Text>) : (<Text>Hello Tsx World</Text>)
return <SafeAreaView>{ child }</SafeAreaView>
}
배열
export default function App(){
const child = [
<Text>Hello Tsx World1</Text>,
<Text>Hello Tsx World2</Text>,
<Text>Hello Tsx World3</Text>,
]
const child2 = [ 1, 2, 3 ].map(i => <Text>Hello Tsx World{i}</Text>)
const child3 = [ 'hello', 'my', 'world' ].map(str => <Text>{str}</Text>)
return <SafeAreaView>{ child }</SafeAreaView>
return <SafeAreaView>{ child2 }</SafeAreaView>
return <SafeAreaView>{ child3 }</SafeAreaView>
const shopping = ["빵", "햄", "우유"]
console.log(shopping[0])
for(let i in shopping){
console.log(shopping[i])
}
// 배열? Object?
const samArr = [ ] // array
const samObj = { } // object
console.log(Array.isArray(samArr))
console.log(Array.isArray(samObj))
const arrSam = ["green", "red", "blue"]
console.log(arrSam.indexOf("green"))
console.log(arrSam.length)
// 배열 정렬
console.log(arrSam.sort()) //올림
console.log(arrSam.reverse()) //내림
const arrNum = [11, 2, 30, 8]
console.log(arrNum.sort()) // ASCII로 정렬
console.log(arrNum.sort((a,b) => a-b)) // 오름
console.log(arrNum.sort((a,b) => b-a)) // 내림
}
-----------------------------------------------------------------------------
< 터미널 >
Hello Tsx World1
Hello Tsx World2
Hello Tsx World3
Hello Tsx World1
Hello Tsx World2
Hello Tsx World3
hello
my
world
빵
빵
햄
우유
true
false
0
3
["blue", "green", "red"]
["red", "green", "blue"]
[11, 2, 30, 8]
[2, 8, 11, 30]
[30, 11, 8, 2]
변수
const global = "전역변수"
const sampleFunc = () => { // arrow(화살표)
console.log('sampleFunc 호출')
const local = "지역변수"
console.log(global)
console.log(local)
}
export default function App(){
sampleFunc()
if(true){
let name = "Kelly"
var hobby = "game"
}
var hobby = "reading"
console.log(name) // let은 범위 중시하여 오류
console.log(hobby)
const age = 24
const myAge = "홍길동 ${age}"
const myAge2 = `홍길동 ${age}` // age value값을 표시하기 위해서 `(backtick)사용
const str = null
if(str === null || str === undefined){
console.log("null 또는 undefined입니다")
}
if(str == undefined){
console.log("== null 또는 undefined입니다")
}
let ex1 = null
ex1 ?? console.log("null입니다") // ??은 null 판별
ex1 = undefined
ex1 ?? console.log("undefined입니다")
ex1 = "Hi Nice to meet you"
console.log(ex1 ?? "null입니다") // NVL IFNULL , null일 경우 ?? 뒤의 값/아닐경우 ex1 값 출력
// 1.
function rectArea(width:any, height:any){
const result = width * height
return result
}
console.log(rectArea(3,5))
// 2.
const rectArea = function(width:any, height:any){
const result = width * height
return result
}
console.log(rectArea(3,5))
// 3.
const rectArea = (width = 7 , height = 9) => { // arrow식
const result = width * height
return result
}
console.log(rectArea(3,5))
console.log(rectArea()) // default값
// rest는 임의 가변인수
const func = (a:any, b:any, ...rest:any) => {
console.log(rest)
}
func(1, 2, 3, 4, 5) // a, b를 제외한 3,4,5를 출력
// Json - Object(객체)
const user = {
name : "홍길동",
message : "나는 성공할 것입니다"
}
const samFunc = ({ message }:any) => console.log(message)
const samFunc2 = (hUser:any) => {
console.log( hUser.name )
console.log( hUser.message )
}
samFunc(user)
samFunc2(user)
------------------------------------------------------------
<터미널>
sampleFunc 호출
전역변수
지역변수
reading
홍길동 ${age}
g홍길동 24
null 또는 undefined입니다
== null 또는 undefined입니다
null입니다
undefined입니다
Hi Nice to meet you
15
15
15
63
[3, 4, 5]
나는 성공할 것입니다.
홍길동
나는 성공할 것입니다.
if / switch / for / while
export default function App(){
const x = 10
if(x === 10){
console.log("x = 10입니다")
}
const color = "red"
if(color === "yellow"){
console.log("yellow입니다")
}else if(color === "red"){
console.log("red입니다")
}else{
console.log("둘 다 아닙니다")
}
// switch
const y = 5
switch(y){
case 1:
console.log("y == 1")
break;
case 5:
console.log("y == 5")
break;
default:
console.log("y == ?")
}
// for문
for(let i = 0; i < 5; i++){
console.log(`${i}번째 루프`)
}
let user = {
name: "성춘향",
age: 16,
address: "남원시"
}
for(let key in user){
console.log(key)
console.log(key + " " + user[key])
}
let arrNum = [10, 20, 30]
for(let i in arrNum){
console.log(i)
console.log(i + " " + arrNum[i])
}
// while
let w = 0
while(w < 3){
console.log(`${w}번째 루프`) // ${w}를 사용하기위해 `사용
w += 1
}
}
----------------------------------------------------------------------------
< 터미널 >
x = 10입니다
red입니다
y == 5
0번째 루프
1번째 루프
2번째 루프
3번째 루프
4번째 루프
name
name 성춘향
age
age 16
address
address 남원시
0
0 10
1
1 20
2
2 30
0번째 루프
1번째 루프
2번째 루프
Object
export default function App(){
const color = "red"
const samObj = {"color": color}
console.log(samObj)
console.log(samObj.color)
const samObj1 = { color } // key = value가 같으면 생략 가능
console.log(samObj1)
const user = {
name:"kim",
id: "jack",
age: 19
}
console.log(user.name)
console.log(user["id"])
const points = {
x : 100,
y : 180
}
points.x = 300
console.log(points)
points.z = 200
console.log(points)
delete points.y
console.log(points)
const pointObj = {a: 10, b: 20, c: 30}
const keys = Object.keys(pointObj) // key값 출력
console.log(keys)
const values = Object.values(pointObj) // values > 배열
console.log(values)
console.log(values[1])
}
---------------------------------------------------------------------------------
< 터미널 >
{"color": "red"}
red
{"color": "red"}
kim
jack
{"x": 300, "y": 180}
{"x": 300, "y": 180, "z": 200}
{"x": 300, "z": 200}
["a", "b", "c"]
[10, 20, 30]
20
Json
export default function App(){
const posts = [
{
id: 1,
content: "Java",
like: 3
},
{
id: 2,
content: "Android",
like: 4
},
{
id: 3,
content: "React Native",
like: 5
},
]
// 1. for > i:index
for(let i = 0; i < posts.length; i++){
console.log(`타이틀: ${posts[i].content}, 좋아요: ${posts[i].like}`)
}
// 2. froEach > post:객체
posts.forEach((post) => {
return console.log(`타이틀: ${post.content}, 좋아요: ${post.like}`)
})
// 3.
const objMap = posts.map((post) => {
return `타이틀: ${post.content} 좋아요: ${post.like}`
})
console.log(objMap)
}
-------------------------------------------------------------------------------
< 터미널 >
타이틀: Java, 좋아요: 3
타이틀: Android, 좋아요: 4
타이틀: React Native, 좋아요: 5
타이틀: Java, 좋아요: 3
타이틀: Android, 좋아요: 4
타이틀: React Native, 좋아요: 5
["타이틀: Java 좋아요: 3", "타이틀: Android 좋아요: 4", "타이틀: React Native 좋아요: 5"]
모듈
// 외부 Welcome 모듈 불러오기 위한 주소
import Welcome from "./src/component/Welcome";
// 함수를 모듈화 시킴 / props:매개변수,공통인자 / 모듈의 첫자는 대문자
// props.name의 name은 <Welcome>의 name값을 가져옴
function Welcome(props:any){
return (
<View>
<Text> Hello Welcome{ props.name } </Text>
<Text> 나이:{props.age} </Text>
</View>
)
}
// function Welcome이 아래의 하나하나 적용
export default function App(){
return(
<View>
<Welcome name="홍길동" age="24"></Welcome>
<Welcome name="성춘향" age="21"></Welcome>
<Welcome name="일지매" age="27"></Welcome>
</View>
)
}
또는 Welcome을 다른 파일로 만들어서 가져오기 가능(단, 본문의 funcion Welcome은 주석처리)
* src/component/Welcome.tsx 생성
- Welcome.tsx -
import React from "react";
// export default 외부에서 불러오기 위해서
export default function Welcome(props:any){
return (
<View>
<Text style={styles.text}>
Hello Welcome{ props.name }
</Text>
<Text style={styles.text}> 나이:{props.age} </Text>
</View>
)
}
모듈2
// src/screens/NamedExportModule.tsx생성
// src/screens/NamedImportModule.tsx생성
NamedExportModule에서 함수를 생성하여 NamedImportModule에서 받아 App.tsx로 가져옴
<App.tsx>
import React from "react";
import { Text, View } from "react-native";
import NamedImportModule from "./src/screens/NamedImportModule";
export default function App(){
return(
<View>
<Text>Hello Tsx</Text>
<NamedImportModule />
</View>
)
}
<NamedExportModule.tsx>
import { tsLiteralType } from "@babel/types";
import React from "react";
import { Text, View } from "react-native";
// 변수
const sampleVar = "sample variable"
// 함수
const sampleFunc = () => "sampleFunc() 호출"
/* arrow함수와 같음
const sampleFunc = function(){
return "sampleFunc() 호출"
}
*/
// number(숫자함수) = int + double int,double 자료형이 없음
const sampleNumFunc = (num1:number, num2:number) => (num1 * num2)
// object == json
const json = [
{
seq: 1,
title: "apple",
content: "사과"
},
{
seq: 2,
title: "strawberry",
content: "딸기"
},
{
seq: 3,
title: "shine musket",
content: "샤인 머스켓"
},
]
const list = () => {
// element는 임의 변수, map() => {return()} : json을 element로 리스트 만들어 출력
return json.map((element) => {
return(
<View key={element.seq} style={{margin: 10}}>
<Text>{element.seq} {element.title}</Text>
<Text>{element.content}</Text>
</View>
)
})
}
// 가져나갈 변수와 함수
export { sampleVar, sampleFunc, sampleNumFunc, list }
<NamedImportModule.tsx>
import React from "react";
import { Text, View } from "react-native";
import {sampleVar, sampleFunc, sampleNumFunc, list} from "./NamedExportModule"
export default function NamedImportModule(){
return(
<View>
<Text>NamedImportModule</Text>
<Text>{ sampleVar }</Text>
<Text>{ sampleFunc() }</Text>
<Text>{ sampleNumFunc(3, 6) }</Text>
<View>{ list() }</View>
</View>
)
}
모듈2
// src/screens/ObjectExportModule.ts 파일생성
// src/screens/ObjectImportModule.tsx 파일생성
<App.tsx>
import React from "react";
import { SafeAreaView, Text } from "react-native";
// ObjectImportModule로 부터 데이터를 가져온다
import NamedImportModule from "./src/screens/ObjectImportModule";
export default function App(){
return(
<SafeAreaView>
<Text>App</Text>
<NamedImportModule></NamedImportModule>
</SafeAreaView>
)
}
<ObjectExportModule.ts>
import React from "react";
// Module
// callback : 함수를 자동 호출
const sampleCallbackFunc = () => {
console.log("123")
// "456"은 1000ms뒤에 자동실행
setTimeout( () => console.log("456"), 1000 )
console.log("789")
}
// template(형태)
class User{
name: String
age: number
constructor(name:String, age:number){
this.name = name
this.age = age
}
UserAge(){
return `${this.name}님은 ${this.age}살입니다`
}
}
export{ sampleCallbackFunc, User }
<ObjectImportModule.tsx>
import React from "react";
import { Text, View } from "react-native";
import { sampleCallbackFunc, User } from "./ObjectExportModule";
// function 밖/안 둘다 생성 가능
const newUser = new User("성춘향", 17)
export default function NamedImportModule(){
return(
// function 밖/안 둘다 생성 가능
sampleCallbackFunc()
<View>
<Text>NamedImportModule</Text>
<Text>name:{ newUser.name }, age:{ newUser.age }</Text>
</View>
)
}
'ReactNative' 카테고리의 다른 글
[React Native] 2 (0) | 2022.03.04 |
---|
댓글