반응형

TouchableOpacity / TouchableHighlight / TouchableWithoutFeedback / Pressable

Props로 onPress로 이벤트를 부여할 수 있다.

TOpacity 경우 천천히 투명도가 0에서 1로 가는 느낌이고

THighlight 경우 반짝 하는 느낌

TWithoutFeedback은 아무 효과가 없다

또한 문서를 참조하여 props를 추가해 다른 효과들을 바꿔줄 수 있다.

Pressalbe은 TWithoutFeedback 과 비슷하지만 더 새로운 것이다. 이를 가지고 onLongPress같은 것들을 사용할 수 있다.

 

import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  TouchableHighlight,
  TouchableWithoutFeedback,
  Pressable,
} from "react-native";
export default function App(){
	const [active, setActive] = useState(true);
	const travel = () => setActive(false);
	const work = () => setActive(true);
	return (
		<View style={styles.container}>
			<StatusBar style="auto" />
			<View style={styles.header}>
				<TouchableOpacity onPress={work}>
					<Text>
						Work
					</Text>
				</TouchableOpacity>
				<TouchableOpacity onPress={travel}>
					<Text>
						Travel
					</Text>
				</TouchableOpacity>
			</View>	
		</View>	
	);
}

 

TextInput

import {StatusBar} from "expo-status-bar";
import {
  StyleSheet,
  Text,
  View,
  TextInput,
} from "react-native";
import {theme} from "./color";
import {useEffect, useState} from "react";

export default function App() {
  const [text, setText] = useState("");
  const travel = () => setActive(false);
  const work = () => setActive(true);
  const textChange = (payload) => setText(payload);
  return (
    <View style={styles.container}>
      <StatusBar style="auto" />
      <View>
        <TextInput
          style={styles.input}
          placeholder={active ? "ADD TODO" : "WHERE DO YOU WANNA GO?"}
          keyboardType="default"
          returnKeyType="done"
          onChangeText={textChange}
          onSubmitEditing={addTodo}
          value={text}
        />
      </View>     
    </View>
  );
}

//style
input: {
    backgroundColor: "white",
    paddingVertical: 10,
    paddingHorizontal: 20,
    borderRadius: 20,
    marginTop: 20,
    fontSize: 18,
    marginVertical: 20,
  },

 

처음에 TextInput사용하게 되면 화면에 나오지 않아 당황할수도 있다. 그럴땐 스타일링을 줘 배경색을 다르게 해보자.

keyboardType으로 모바일의 키보드 종류에 맞는 배열로 바꿔줄수 있다.

props는 android에서 호환되는것과 ios에서 호환되는것들이  혹은 둘다 호환되는 것들이 있으니 잘 참고해서 사용하자

onSubmitEditing으로 submit을 할수 있게 만들수 있다.

 

AsyncStorage

npx expo install @react-native-async-storage/async-storage

 

이를 사용하기 위해서는 try catch 문을 사용할것을 강력권고한다.

Alert API

Alert API는 대화창을 실행시킨다. 두가지 옵션이 있는데 alert()과 prompt()가 잇는데 prompt는 ios에서만 작동 가능하다.

Alert.alert(제목, 내용?, 버튼?, 옵션?)
//? 표시는 type자로 required가 아님을 나타냄
// 버튼은 array of object로 text / onPress / style 을 넣을 수 있으며 style은 ios 한정이다.
  const deleteTodo = async (key) => {
    Alert.alert("R U SURE?", "REALLY DELETE?", [
      {text: "cancel"},
      {
        text: "ok",
        style: "destructive",
        onPress: async () => {
          const newToDos = {...toDos};
          delete newToDos[key];
          setToDos(newToDos);
          await saveToDos(newToDos);
        },
      },
    ]);
    return;
  };

 

728x90

'React-Native > Basic with Expo' 카테고리의 다른 글

React-Native__Basic-001 with EXPO  (0) 2023.11.16
React-Native__Basic-002 with EXPO  (0) 2023.11.15
반응형

React - Native SetUp

리액트 네이티브를 하기 위해서는 셋업과정이 필요하다. 

안드로이드를 개발하기위해서 안드로이드 스튜디오 , 안드로이드 sdk , 시뮬레이터 그밖의 개발도구를 다운받아야하고 JAVA를 사용해야한다. 마찬가지로 ios를 개발하기 위해서 Xcode,시뮬레이터를 다운받아야한다. 이 경우에는 조금 쉬우나 안드로이드 스튜디오를 세팅하는것은 조금 까다롭다. 

 

앱이 구동되는 과정에서 여러 과정들이 있는데 이번 기본기를 배우는 시간에는 웹페이지를 만드는 것 처럼 자바스크립트와 마크업 그리고 스타일링으로 구성하여 제작할것이다. 이외에 것은 EXPO라는 것을 사용해서 그 어떤 시뮬레이터나 JAVA, Xcode같은 것들을 설치하지 않고  Apple Store / Google Play 에 배포가 가능하게 끔 만들 것이다.

 

Expo CLI 설치

1. expo를 사용하기 위해서 CLI를 설치해야한다. 

npm install -g expo-cli

https://docs.expo.dev/archive/expo-cli/

2. 만약 Mac 사용자라면 Watchman이라는 것을 다운받아야한다. (윈도우 사용자는 안해도됨)

brew update
brew install watchman

 

3. 모바일 디바이스 Apple Store / Google Play에서 Expo GO를 찾아 설치한다. expo 회원가입하고 로그인을 해준다.

vscode에 회원가입한 이메일주소와 비밀번호를 기재해 로그인한다.

expo login

 

 

Expo 프로젝트 시작

1. 프로젝트 생성 및 시작

npx create-expo-app 프로젝트이름

cd 프로젝트이름
npx expo start

 

이렇게 되면 vscode 콘솔창에 qr코드도 나오고 ios / android 시뮬레이터로 실행할수 있게 단축키가 있다. 웹으로도 볼수있고 모바일 디바이스에서 설치했던 EXPO Go를 통해 QR코드를 찍고 볼 수 있다. 

App.js의 내용을 그대로 볼 수 있다. 

 

Welcome. React Native.

Core Components

리액트 네이티브는 웹사이트가 아니기 때문에 div, span, p 이런 HTML ELEMENT들은 사용할 수가 없다. 코어 컴포넌트를 사용해서 접근 해야한다. 

React Native Andriod IOS WEB
<View> <ViewGroup> <UIView> <div>
<Text> <TextView> <UITextView> <p>
<Image> <ImageView> <UIImageView> <img>
<ScrollView> <ScrollView> <UIScrollView> <div>
<TextInput> <EditText> <UITextField> <input type="text">

 

React - Native Styling

또한 웹과 다르게 스타일도 몇몇은 비슷하게 가져왔지만 몇몇은 사용할수가 없거나 하나하나씩 지정을 해줘야 한다.

style은 StyleSheet.create({})를 사용해 내부에 오브젝트를 만들어 원하는 요소에 작업을 해주거나 style={{ 스타일 }}을 통해 직접 스타일링 할 수 있다.

 

Caution : React Native Core Components

초기 react native에는 수 많은 components들이 있었다. 하지만 모든 Components들을 관리하고 만들고 하는 지원하는 행위가 어렵다는것을 깨달았다. 그래서  React Native에서는 몇몇 component들을 없애고 제일 핵심적인 것들만 남겼다. 대신에 이제 Third Party Packages를 사용해 원하고자 하는 기능들을 설치하길 권고 하고 있다.

  • 리액트 네이티브 디렉토리( https://reactnative.directory/ )

위의 주소에 Third Party Package들이 있다. 

특히 EXPO에서는 이를 엄청 중요시 여긴 나머지 EXPO SDK를 만들었다.

리액트네이티브에 없다면 여기서 찾아 사용하면 된다.

728x90

'React-Native > Basic with Expo' 카테고리의 다른 글

React-Native__Basic-003 with EXPO --TODO  (0) 2023.11.18
React-Native__Basic-002 with EXPO  (0) 2023.11.15
반응형

React Native의 Layout System

React Native에서는 display:block , inline-block,grid 이러한 것들이 없다.

오로지 flexbox뿐이다. 

웹에서는 display:flex ; flex-direction:column을 주어 세로 정렬이 가능했지만 모바일에서는 flex-direction:column이 default 값이다. 또한 <View>사용해 넘차나는 부분을 스크롤할수가 없다.

 

모바일에서는 너비와 높이를 기반한 어떠한것들을 만드는 것은 좋은 생각이 아니다.

flex를 사용한 비율을가지고 만드는 것을 추천한다.

export default function App(){
	return (
    	<View style={{flex:1}}>
        	<View style={{flex:1, backgroundColor:"orange"}}></View>
            <View style={{flex:5, backgroundColor:"blue"}}></View>
            <View style={{flex:2, backgroundColor:"red"}}></View>
        </View>
}

 

또한 작업진행시 바탕색을 넣으며 비율을 보며 작업을 하는게 용의하다

<ScrollView>

export default function App(){
	return (
    	<View style={{flex:1}}>
          <View style={{flex:1, backgroundColor:"orange"}}>
            	<Text>hoho</Text>
                <Text>haha</Text>
                <Text>hehe</Text>
            </View>
            <View style={{flex:5, backgroundColor:"blue"}}>
            	<Text>huhu</Text>
                <Text>hyhy</Text>
                <Text>papa</Text>
            </View>
            <View style={{flex:2, backgroundColor:"red"}}>
            	<Text>pepe</Text>
                <Text>popo</Text>
                <Text>pipi</Text>
            </View>
        </View>
}

이렇게 만들시 웹과 다르게 스크롤이나 드래그를 할 수  없다.

 

이걸 스크롤하게 만들기 위해서는 

export default function App(){
	return (
    	<ScrollView style={{flex:1}}>
          <View style={{flex:1, backgroundColor:"orange"}}>
            	<Text>hoho</Text>
                <Text>haha</Text>
                <Text>hehe</Text>
            </View>
            <View style={{flex:5, backgroundColor:"blue"}}>
            	<Text>huhu</Text>
                <Text>hyhy</Text>
                <Text>papa</Text>
            </View>
            <View style={{flex:2, backgroundColor:"red"}}>
            	<Text>pepe</Text>
                <Text>popo</Text>
                <Text>pipi</Text>
            </View>
        </ScrollView>
}

이렇게 하면 세로로 드래그할수 있는 화면이 나오게 된다.

 

이것을 가로로 드래그 할 수 있는 화면으로 구성하려면

<ScrollView 
  horizontal
  pagingEnabled
  showHorizontalScrollIndicator
  contentContainerStyle={{flex:1}}
  ></ScrollView>

horizontal을 추가하면된다. 또한 style은 그냥 style을 사용하면 안되고 contentContainerStyle을 사용해야한다.

pagingEnabled을 추가하게 되면 자유분방한 스크롤이 하나씩 넘어가게 끔 조정된다.

showHorizontalScrollIndicator는 overflow-x:hidden 정도로 생각하면된다.

그밖에 props가 많으니 document을 보고 참고하자.

 

디바이스 화면의 크기를 알아내는 방법은 Dimensions를 사용하면 된다.

const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;

const {width:SCREEN_WIDTH,height:SCREEN_HEIGHT} = Dimensions.get('window')

 

User Location

유저의 위치를 알기 위한 방법이다.

npx expo install expo-location

 

먼저 권한 요청을 해야한다. 권한 요청은 Location.requestForegroundPermissionAsync()를 사용하며 꼭 import * as Location from 'expo-location'을 작성하여 불러오자

import {StatusBar} from "expo-status-bar";
import * as Location from "expo-location";
import {useEffect, useState} from "react";

const year = new Date().getFullYear();
const month =
  new Date().getMonth() > 10
    ? "0" + (new Date().getMonth() + 1)
    : new Date().getMonth() + 1;
const date =
  new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate();

const base_url = (lat, lon) =>
  `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;

const {width: SCREEN_WIDTH} = Dimensions.get("window");

export default function App() {
  const [city, setCity] = useState("Loading.. ");
  const [day, setDay] = useState([]);
  const [ok, setOk] = useState(true);
  
  //권한 요청
  const getLocateWeather = async () => {
    const {granted} = await Location.requestForegroundPermissionsAsync();
    if (!granted) {
      setOk(false);
    }
   
}
  useEffect(() => {
    getLocateWeather();
  }, []);

 

다음은 현재 위치를 알아내기 위해 Location.getCurrentPositionAsync()를 사용한다.  여기서는 몇가지 옵션을 받는데 그중하나가 accuracy인데 얼마나 정확하게 나오게 할지에 대한 부분이다. 여기서 디버깅하면 위도와 경도를 알아낼 수 있다.

export default function App() {
  const [city, setCity] = useState("Loading.. ");
  const [day, setDay] = useState([]);
  const [ok, setOk] = useState(true);

  const getLocateWeather = async () => {
    const {granted} = await Location.requestForegroundPermissionsAsync();
    if (!granted) {
      setOk(false);
    }
    
    const {
      coords: {latitude, longitude},
    } = await Location.getCurrentPositionAsync({accuracy: 5});
   } 
   
  useEffect(() => {
    getLocateWeather();
  }, []);

 

이것을 가지고 본인이 살고 있는 지역을 알아낼 수 있다. 위치를 알아내는 방법은 크게 두가지 인데 geocodeAsync(address) ((주소를 받아서 위도와 경로로 변환)와 reverseGeocodeAsync(location,option) ((위도와 경도를 이용하여 주소를 반환)) 이다.

Location.reverseGeocodeAsync(location,option)를 사용하면 된다. 여기서는 위치와 옵션을 설정한다.

export default function App() {
  const [city, setCity] = useState("Loading.. ");
  const [day, setDay] = useState([]);
  const [ok, setOk] = useState(true);

  const getLocateWeather = async () => {
    const {granted} = await Location.requestForegroundPermissionsAsync();
    if (!granted) {
      setOk(false);
    }
    const {
      coords: {latitude, longitude},
    } = await Location.getCurrentPositionAsync({accuracy: 5});

    const location = await Location.reverseGeocodeAsync(
      {latitude, longitude},
      {useGoogleMaps: false}
    );
}
  useEffect(() => {
    getLocateWeather();
  }, []);

이것을 디버깅하게 되면 ios 시뮬레이터는 항상 미국에 위치해있다고 디버깅 할 것이다. 디버깅을 추적하여 데이터값들을 입력해주면 된다.

 

ICONS 

두번째 주소로 들어가 원하는 아이콘을 찾아서 누른후 나오는 코드들만 추가하면 끝이다. 같은 종류의 코드를 하는것이 tree shaking에 좋을 듯하다.

 

728x90

'React-Native > Basic with Expo' 카테고리의 다른 글

React-Native__Basic-003 with EXPO --TODO  (0) 2023.11.18
React-Native__Basic-001 with EXPO  (0) 2023.11.16

+ Recent posts