react native guides 보기전에
TRANSCRIPT
Why you should consider React Native ?
• Native와친화력
• 빠른학습속도
• 방대한 생태계
• 훌륭한개발환경
출처 : https://www.smashingmagazine.com/2016/04/consider-react-native-mobile-app/
1. Xcode 설치
2. Dependency 설치
3. React Native CLI 설치
0. 웬만하면 Mac에서개발하자@@
앱스토어에서설치
$ brew install node
$ brew install watchman
$ brew install flow
// node는기본// 파일변경감시// 정적타입검사기
$ npm install -g react-native-cli
4. 프로젝트만들기$ react-native init RNExam
$ cd RNExam
$ react-native run-ios
// ReactNative 프로젝트자동생성// 프로젝트로들어가기// ios용시뮬레이터실행
Root
Component Component
ComponentComponentComponent
AppRegistry
AppRegistry에 root Component를등록하여 ReactNative 에게알려준다.
AppRegistry
registercomponent
StyleSheet
• 기존 inline style방식으로객체를통해스타일적용
• 복잡도에따라 css stylesheet를추상화한 ‘StyleSheet’ 객체를통해컴포넌트 css 적용
• React 와같이 camelcase 방식으로네이밍
Networking
- 기본적으로 ‘Fetch API’ 를지원함으로써 XMLHttpRequest 방식안써도된다.
기존 Ajax 방식처럼쉬운방법
비동기호출을 Promise객체로 wrapping 하여원하는결과를반환받는방식
ES7에서제공하는 async/await 를이용한비동기호출반환
웹 CSS 에 ‘Flex’ 와비슷한방식으로다양한기기(사이즈)에서동일한 ‘Layout’을표현하기위한알고리즘
• flexDirection
• alignItems
• justifyContent
다음 3가지속성의조합으로레이아웃을표현
FlexBox
justifyContent
• 주축(primary axis)에따라분포도(distribution)를결정
• flex-start (상단)
• center (중앙)
• flex-end (하단)
• space-around (주변공백)
• space-between (사이공백)
flex-start
flex-endspace-around
space-between
center
alignItems
• 보조축에따라 children요소정렬
• 기본축이 row이면, column(그반대는반대)
• flex-start
• center
• flex-end
• stretch
center flex-start
flex-endstretch
Gesture Life cycle
Gesture Responder System
출처 : https://rangle-io.gitbooks.io/react-native-workshop/content/book/misc/gesture-responder-system/
Gesture Life cycle
이뷰가터치응답자로지정되어시작되어진다.
View가 true / false 에따라응답자로응답할지결정
터치이동중
터치가끝나면(손가락을업)
다른뷰에서응답자가되려고한다. 현재뷰응답자를이제해제할것인가!?
다른뷰에서가져오거나, OS에서응답을가져온다.(IOS제어센터/알림센터에서발생)
버블링을따르기때문에부모가응답자가되길원하는경우사용
Gesture Native Event
• changedTouches
• identifier
• locationX
• locationY
• pageX
• pageY
• target
• timestamp
• touches
PanResponder
상위레벨에서조정할수잇는제스처인터페이스
여러가지터치를단일제스처로재조정하는일을한다.
장시간실행되는 JS이벤트로부터활성제스쳐를보호하는 ‘InteractionManager’ 를가지고있다
native event 객체와함께새로운 gestureState를제공
• stateID
• moveX
• moveY
• x0
• y0
• dx
• dy
• vx
• vy
• numberActiveTouches
Best Pratices
• Feedback/highlighting
• 터치처리와해제시액션피드백사용자에게제공
• Cancel-ability
• 터치중드래그하여중간터치를중지할수있는액션
Tappable Components
• Tapping(start/end)은 `onPress`
이벤트가호출되 props로전달
• Long press 는 `onLongPress`호출
• Tapping이발생함에따른피드백제공
Tappable Feedback
TouchableHighlight• 버튼클릭시버튼의배경이어두워진다.
TouchableNativeFeedback• Android에서사용자터치에반응한잔물결액션요소
TouchableOpacity• 버튼터치하는동안버튼의불투명도가감소• 뷰계층변경없이진행
TouchableWithoutFeedback• 아무액션을원하지않을경우
ScrollView
• ScrollView는수직/수평스크롤가능
• `pagingEnabled` prop로 swipe
제스처가능
• Android에서 `ViewPaerAndroid`
컴포넌트이용
scroll view
ReactNative 는 2가지 Animation system 제공
Animated LayoutAnimation
상호작용하는애니메이션
Global layout transactions
간결한표현설계
다양한애니메이션기능
입/출력사이에변환및시간기반시작/중지에중점을둔애니메이션
순차/병렬로 play 가능
애니메이션끼리결합가능
보간법을통해각속성실행
다른애니메이션을트래킹하여다이나믹하게값조정가능
현재애니메이션값을알수있다.
( stopAnimation(cb) / addListener(cb) )
serializeable하게설계되어, native driver를사용native code platform으로보내어방해없이 UI스레드수행
Flexbox layout 업데이트시유용
• requestAnimationFrame
• 모든 frame이 flush된이후에실행
• setTimeout(fn, 0)
• 매우빠르게곧장실행된다.
• setImmediate(fn)
• 다른배치작업완료후 native로가기전 JS 실행블록맨뒤에배치되어실행
• setImmediate 콜백내에 setImmediate 호출시바로실행된다.
• Promise
• 비동기로작동하며, setImmediate를사용한다.
기존 Native 함수지원
InteractionManager
cost가많이드는작업을피하는것을원칙싱글스레드(JS)에서 상호작용 하는 애니메이션이 완료된후긴배치작업진행하도록스케쥴링
App에서애니메이션시작시상호작용할 ‘handle’ 생성완료되면삭제
TimerMixin
마운트해제후 Timer가실행되는치명적인이슈발생
왜갑자기전설의믹스인이 ?
어떻게해결?
‘setTimeout()’ -> ‘this.setTimeout()’ 으로변경함으로써해결this를삽입
state/props 없이컴포넌트를직접변경할니즈존재
ex) 특정 DOM 접근하여직접수정하는경우
어떻게?
setNativeProps
빈번한 re-rendering으로병목발생시사용하세요
언제쓰일까?
컴포넌트 계층/많은 뷰를 렌더링 하는데 필요한 오버헤드 피하기위해연속적인애니메이션생성하는데만사용
‘TouchableOpacity’ 는 내부적으로 setNativeProps를 사용하여 불투명도조절
setNativeProps가 안되면 위와같이 직접 state를 업데이트 해줘야 하는불편함
이슈• Native layer(Dom, UIView)에 상태를 저장하기 때문에 data
tracking 이슈해결 => setState / shouldComponentUpdate 로문제해결
• 중첩 컴포넌트는 Native View에 근거하지 않으므로setNativeProps 호출이불가
• Touchable 자식은 native이여야 한다 blahbla error
발생
Native 컴포넌트로랩핑하지않은이상style props를전달해야함
요로코롬
Native 컴포넌트인 View 로랩핑하여해결
필요구성요소실행단계• JS 번들• Native모듈• JS-VM
Native property/config 정의
App 실행!!
출처 : https://www.slideshare.net/TadeuZagallo/react-native-internals
ReactNative work flow
JS실행되어 Native 호출
Layout 구성및 RenderUser
action
User Action -> UIKit->Native -> JS 호출
출처 : https://www.slideshare.net/TadeuZagallo/react-native-internals
그외지원내역 : https://github.com/facebook/react-native/blob/master/babel-preset/configs/main.js#L16
Transform 지원내역
In-App Dev Menu
• IOS Hardware menu 열기
• iphone 시뮬레이터실행시“Command ⌘ + D”
• Android 에뮬레이터실행시“Command ⌘ + M”
• release 빌드시 disable 된다.
Reloading
• App Reload• 변경시재컴파일해서변경하는대신 JS를즉시 reload가능• Developer Menu 에서 “Reload” 클릭• “Command ⌘ + R” ( iOS 시뮬레이터 )
• “R” 두번누르기 ( Android 시뮬레이터)
• Live Reload• 코드변경시자동 reload
• Developer Menu에서 “Enable Live Reload” 활성화클릭
• Hot Reload• React Hot Reload 와같은동작방식• Developer Menu에서 “Enable Hot Reloading” 활성화클릭
• 예외사항(무조건 rebuild 해야하는상황)• IOS/Android에이미지리소스파일추가시• 네이티브(iOS/Android) 코드수정시
Errors Trace
• Errors• 에러발생시화면전체에 RedBox와함께에러메세지출력• “console.error()” 로메뉴얼하게트리거가능
• Warnings• 화면전체에 yellow box 와함께메세지출력• “console.warn()”으로가능• Dev환경에서 “console.disableYellowBox = true;’” 를통해 disable 가능
Native Log 확인
• IOS/Android 앱실행시터미널에서 Log 출력가능
$ react-native log-ios
$ react-native log-android
• IOS시뮬레이터내에서확인방법
• “Debug -> Open System Log .. “
• Android Device/emulator 내에서확인방법
• “adb logcat* : S ReactNative : V ReactNativeJS : V” 터미널에서실행
Chrome Developer Tools
• 기존 JS 코드디버깅하는걸원할경우• Developer Menu에서 “Debug JS Remotely” 활성화• “http://localhost:8081/debugger-ui" 오픈하여확인• Chrome Inspector 오픈
• Device 디버깅하는방법• Developer Menu에서 “Debug JS Remotely” 활성화• iOS 디바이스
• RCTWebSocketExecutor.m 에서 “localhost” 부분을본인 IP로변경
• Android 디바이스• v5.0이상디바이스에서 USB 연결상태인경우
• “adb” CLI 로포워딩 => “adb reverse tcp:8081 tcp:8081”
• Developer Menu에서 “Dev Settings” 클릭후본인 IP와일치하도록“Debug server host for device” 설정업데이트
• iOS• Integration Tests
• JS와 Native를 Bridge통해통신하는통합컴포넌트를보다쉽게테스트할수있는기능제공
• 주요구성요소인 “RCTTestRunner / RCTTestModule”
• RCTTestRunner
• ReactNative 환경설정, XCode XCTestCases 실행기능제공• RCTTestModule
• JS에 NativeModules.TestModule로내보내진다.
• Javascript Tests• Jest : JS만테스팅하는 Node기반 CLI test
• react-native 프로젝트를통해테스트코드확인가능• __tests__/TouchableHighlight-test.js 에서예제확인
• Flow : 정적타입체커
• Android• Unit Tests
• emulator에선테스트가안되어 Java8(JDK8) 설치필요• Buck build tool 설치• ./ReactAndroid/src/tests 에서테스트코드예제확인가능
• Integration Tests
• Android NDK 설치필수• Buck build tool 설치• ./scripts/run-android-emulator.sh 확인• ./scripts/run-android-local-integration-tests.sh 확인• ./ReactAndroid/src/androidTest 확인
• IntegrationTestHarnessTest.js
• UIExplorerIntegrationTests.m
• IntegrationTestsApp.js
처음설치했던 react-native-cli 말고,
각프로젝트별내장된 React Native CLI를이야기합니다.
react-native
local-cli
command.js
link
local프로젝트용 CLI
react-native link 명령어관련내용들
react-native 명령어추가
light하게사용하는데필요한기능은아닌듯.
Plaform(Android/iOS)용 module
runtime시실행중인 OS 감지가능 Platform.select 메서드를통해현재사용중인 OS의값을반환한다.OS를 key로하는객체반환
OS별컴포넌트반환방식지정가능
Android Version 체크가능
통합리소스관리장점
• 동일한시스템, 폴더에서플랫폼으로제공
• 전역 namespace 때문에, 이름충돌이없다.
• 실제로사용하는 Image만패키징
• 재컴파일할필요가없다.(시뮬레이터 realod)
• Image는 npm을통해배포가능
Network Images
• 동적으로 Image를 binary로로드할경우 Image dimension을수동으로지정해야한다• App Transfer Security 로인해 HTTPS 로요청해야한다.
Cache Control(only iOS)
• local cache에있는이미지로먼저표시하는방식제공• default : 기본 native 플랫폼전략사용• reload : 기존캐시데이터사용하지않고원래 source에서로드• force-cache : age / expiration date 무시하고무조건캐시데이터사용후없는경우원래 source 호출• only-if-cached : 기존캐시데이터를사용하되없을경우원본 resource를호출하지않고실패로간주
Local Filesystem Images
• Image.xcassets 외부에있는로컬리소스는 CameraRoll 섹션참고
• iOS는카메라롤의동일한이미지에대해다양한사이즈저장하여성능이슈해결• 200x200 미리보기에 3264x2448 원본이미지를사용하지않게한다.
기존웹에서 Image 리소스로드시 flicking 이슈
웹브라우저에서 Image 크기미지정후로드할경우 0x0 크기로렌더링하고리소스로드후Image 렌더링되는이슈발생iOS saves multiple sizes for the
same image in your Camera
Roll, it is very important to pick
the one that's as close as
possible for performance
reasons. You wouldn't want to
use the full quality 3264x2448
image as source when
displaying a 200x200 thumbnail.
If there's an so you don't have
to worry about writing the
tedious (and error prone) code
to do it yourself.
iOS saves multiple sizes for
the same image in your
Camera Roll, it is very
important to pick the one
that's as close as possible
for performance reasons.
You wouldn't wantf.
but,
ReactNative 는애초에크기가장착되어로드된다.
Source as an Object
• 기존 Image “src” 속성을 “source” 으로변경• uri 속성은 string이아닌 object로대응
source object에메타데이터첨부가가능해져다양한속성정의가능
Background Image
배경이미지를넣기위해서 <Image>에중첩하여 <Text> 요소추가
iOS Border Radius Style
현재 iOS에서는모서리둥근스타일은무시된다.
• borderTopLeftRadius
• borderTopRightRadius
• borderBottomLeftRadius
• borderBottomRightRadius
ActivityIndicator
Button
DatePickerIOS
DrawerLayoutAndroid
FlatList
Image
KeyboardAvoidingView
ListView
MapView
Modal
Navigator
NavigatorIOS
Picker
PickerIOS
ProgressBarAndroid
ProgressViewIOS
RefreshControl
ScrollView
SectionList
SegmentedControlIOS
Slider
SnapshotViewIOS
StatusBar
Switch
TabBarIOS
TabBarIOS.Item
Text
TextInput
ToolbarAndroid
TouchableHighlight
TouchableNativeFeedback
TouchableOpacity
TouchableWithoutFeedback
View
ViewPagerAndroid
VirtualizedList
WebView
37개컴포넌트제공