React-Native__Basic-002 with EXPO
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
유저의 위치를 알기 위한 방법이다.
- expo locationr 관련 문서 (https://docs.expo.dev/versions/v49.0.0/sdk/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
- Expo - Icons 관련 (https://docs.expo.dev/guides/icons/) (https://icons.expo.fyi/Index)
두번째 주소로 들어가 원하는 아이콘을 찾아서 누른후 나오는 코드들만 추가하면 끝이다. 같은 종류의 코드를 하는것이 tree shaking에 좋을 듯하다.