More Inside The Classes

2y ago
42 Views
3 Downloads
1.30 MB
71 Pages
Last View : 16d ago
Last Download : 3m ago
Upload by : Elise Ammons
Transcription

React NativeShan-Hung Wu & DataLabCS, NTHU

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations2

Prerequisite:HTML5CSS3ES6React JSRedux3

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations4

React Native A framework that let you writeapps in React JS way5

Installation Guide react-native init HelloReactNative// iOS react-native run-ios// on Android, start AVD first react-native run-android6

HelloReactNative react-native init HelloReactNative// in HelloReactNative/index.[ios android].jsimport React from 'react';import {AppRegistry, Text} from 'react-native';class MyApp extends React.Component {render() {return ( Camel-case convention Text Hello world! /Text ); ES6 features} JSX with RN ctNative',() MyApp);– *.js files AppRegistry instead ofReactDOM7

Running and Dynamic Reloading Packager is like Webpack Reload:– Cmd R (iOS)– R R (Android) Dev menu:– Cmd D (iOS)– Cmd M (Android) Debugging:– console.log()– debugger8

Why app written by JS is native?9

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations10

Native AppsYour App (C or Swift)3rd Party LibsSDKs, Standard LibsiOSYour App (Java or Kotlin)3rd Party LibsSDKs, Standard LibsAndroid Different code and language for different OS's11

WebViewAppsYour AppMobile Development Framework(e.g., Apache Cordova, Adobe PhoneGap)WebView APIiOS SDKsAndroid SDKsiOSAndroid Write once, run everywhere Slow and not feeling native12

React-Native AppsYour App(Native UI &Modules)Your App (JS)NPM Pkgs(e.g., React)BridgeNative UI3rd Party LibsReact NativeJS RuntimeiOS SDKsiOSYour App(Native UI &Modules)Your App (JS)NPM Pkgs(e.g., React)BridgeNative UI3rd Party LibsReact NativeJS RuntimeAndroid SDKsAndroid JS components render as native ones Learn once, write everywhere13

AppRegistry.runApp('MyApp');v a, C, etc.)[funID, args][funID, args]JSAppRegistry.runApp('MyApp');return ( View . /View ); Calls through bridge are– Asynchronous (event loops are separated)– Batched (to save overhead)14

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations15

RN Components (see Doc) View is like div in HTML Text is like span – Text must be wrapped in Text . /Text Custom components:// in MyComponent.jsexport defaut class MyComponent extends React.Component {render() {.}}// in App.jsimport MyComponent from './MyComponent';// use MyComponent / in render()16

// in App.js MyComponent name {'Bob'} / Props and States,as Usual// in MyComponent.jsclass MyComponent extends React.Component {constructor(props) {.this.state {isNew: true}}render() {const {name} this.props;return ( Text Hello {name}, {this.state.isNew ? 'welcome' : 'welcome back'} /Text );}}17

Redux, as Usualimport {connect} from 'react-redux';class MyComponent extendsrender() {const {name, isNew} return ( Text Hello {name},isNew ? 'welcome'} /Text React.Component {this.props;{: 'welcome back');}}export default connect(state ({isNew: state.user.isNew // 'user' reducer}))(MyComponent);18

Prop, State, orRedux Store?19

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations20

Styling in RN No CSS Instead, assign style prop to componentsrender() {return ( View Text style {{color: 'blue'}} . /Text Text style {styles.red} . /Text // cascade Text style {[styles.red, styles.title]} . /Text /View );}const styles {red: {color: 'red'},title: {fontSize: 24}}; List of supported styles Values have no unit21

import {StyleSheet} from'react-native';StyleSheetrender() {return ( View View style {styles.listItem} . /View View style {styles.listItem} . /View . View style {styles.listItem} . /View /View );}const styles StyleSheet.create({listItem: {.}}); Allows multiple native components torefer to same style object (by ID)– Useful for, e.g., list items22

Sizing and Layout Every “container” component(e.g., View) is a flexbox– flexDirection: ‘column’ by default– justifyContent: ‘flex-start’– alignItems: ‘stretch’ View flex: 1flex: 2 Contained component:– alignSelf– width/height: number– flex: number Use inspector at runtimeflex: 3 /View 23

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations25

Event Handlingrender() {return ( TouchableHighlightonPress {this.handlePress}onLongPress {() alert('Yo')} View Text Press me! /Text /View /TouchableHighlight );} TouchableHighlight TouchableOpacity TouachableNativeFeedback (Android only)26

Controlled Componentsrender() {return ( TextInputplaceHolder 'Type here'value {this.state.text} // controlled componentonChangeText {text this.setState({text})}ref {el this.inputEl}onEndEditing {() {.this.inputEl.clear();}}/ );}27

How are native eventshandled in JS?28

NativeUI (Main) ThreadNativeModules ThreadJS ThreadEvent QueueEvent QueueEvent QueueThreads and Queues29

NativeUI (Main) ThreadNativeModules ThreadJS ThreadEvent QueueEvent QueueEvent QueueEvent E.g., touch, I/O, or networking event30

NativeUI (Main) ThreadNativeModules ThreadJS ThreadEvent QueueEvent QueueEvent QueueEventRun Handler JS thread calls yourhandler via thebridge31

NativeUI (Main) ThreadNativeModules ThreadJS ThreadEvent QueueEvent QueueEvent QueueEventRun HandlerLayout If UI changed in JS, module thread performslayout first (e.g., measuring size of text)32

NativeUI (Main) ThreadNativeModules ThreadJS ThreadEvent QueueEvent QueueEvent QueueEventUpdate UIRun HandlerLayout Then, UI thread renders components33

NativeUI (Main) ThreadNativeModules ThreadJS ThreadIdeally, entire cycle in 16ms (60fps) Offload unnecessary computing to bgEvent Queue– Using, e.g.,EventQueuePromiseAPIEvent QueueTouch EventRun HandlerUpdate UILayout34

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations35

Images// JSX Image source {require('dir/image.png')} style {{.}} / // in dirimage@2x.png // iPhone 7image@3x.png // iPhone 7 Plus or Nexus 5 RN handles off-thread decoding for you Size inferred from source file by default– To scale image dynamically (with flex), set widthand height to undefined Background image? Image source {.} resizeMode 'cover' style {{.}} View . /View /Image 36

Network Images Imagesource {{uri: 'https://./image.png',cache: 'reload' // or 'force-cache' or 'only-if-cached'}}style {{width: 200, height: 200}}onLoad {.}/ RN handles caching for you But you need to specify size manually It's a good practice to display a static placeholderbefore loaded// in JSX{this.state.isLoaded ? Image source {{uri: .}}onLoad {() this.setState({isLoaded: true})} / : Image source {require('dir/placeholder.png')} }37

Font Icons npm install --save react-native-vector-icons react-native link// in JSimport Icon from 'react-native-vector-icons/FontAwesome';// JSX Icon name "rocket" size {30} color "#900" / See more supported fonts and features38

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations39

Networking// GETfetch('https://.').then((res) {if (res.status ! 200) throw new Error('.');return res.json();}).then(data .).catch(err .) Fetch API Plaintext HTTP requestswill be blocked on iOS// POSTfetch('https://.', {– Apps on Apple'smethod: 'POST',shall use HTTPSheaders: {Accept: 'application/json','Content-Type': 'application/json',.}body: JSON.stringify(.)})App Store40

App Transport Security (ATS) Exception// in [PROJ ROOT]/ios/[PROJ NAME]/Info.plist key NSAppTransportSecurity /key dict key NSExceptionDomains /key dict . key yourdomain.com /key dict !--Include to allow subdomains-- key NSIncludesSubdomains /key true/ !--Include to allow HTTP requests-- key NSTemporaryExceptionAllowsInsecureHTTPLoads /key true/ /dict Re-run react-native run-ios /dict /dict 41

Persistent Storage In mobile landscape, Internet may not alwaysbe available It's a good practice to allow offline data access AsyncStorage (global to app):// API similar to HTML5 LocalStorageAsyncStorage.setItem(key, value); // stringsAsyncStorage.mergeItem(key, delta);AsyncStorage.getItem(key).then(value .);AsyncStorage.multiGet(keys).then(values .);42

Persisting Redux States// save when any state changesstore.subscribe(() e.getState()));});// loadAsyncStorage.getItem('states').then(value {store ompose(.));}); You can persist partial states43

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations44

Clone WeatherMoodMobile Checkout the redux-post branch npm install --save \native-base color \react-native-infinite-scroll-view \react-navigation react-native link NativeBase and Color for UI RN Infinite Scroll View React Navigation for client-side routing45

mponentsPostListTodayScreen46

ComponentsDrawerSideBar47

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations48

NativeBase Same component, different (native) looks49

Theme Customization node node modules/native-base/ejectTheme.js vim native-base-theme/variables/platform.js// in app.jsimport {StyleProvider} from 'native-base';import getTheme from './native-base-theme/components';import platform from'./native-base-theme/variables/platform';class MyApp extends React.Component {render() {return ( StyleProvider style {getTheme(platform)} View . /View /StyleProvider );}} Read more about customization50

Platform-Specific Code Platform-specific .ios.jpgimages/banner@2x.android.jpg Or use Platform:import {Platform} from 'react-native';// in JSconst styles StyleSheet.create({toolbar: {height: (Platform.OS 'ios') ? 64 : 56}});51

import {Button} from'native-base';Flat Style Objectsclass MyComponent extends React.Component {render() {return ( Button style {styles.btn} // error Text . /Text /Button );}}const styles StyleSheet.create({btn: {.}}); NB components create StyleSheets automatically– Use plain objects, or– Stylesheet.flatten(styles.btn)52

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations53

ScrollView ScrollViewhorizontal {true}onScroll {e {const y e.nativeEvent.contentOffset.y;.}}style {{flex: 1}} // or set height directly View . /View Image . /Image Text . /Text . /ScrollView Elements can be heterogeneous Horizontal or vertical scroll Unbounded child height must have bounded height54

ListView// in a componentconstructor(props) {.const ds new ListView.DataSource({rowHasChanged: (r1, r2) r1.id ! r2.id});this.state {dataSource: ds.cloneWithRows([{/* r1 */}, .])}} Optimized for large #items:– Lazy and rate-limited row renderingrender() {return (– Only re-renders changed rows. ListView. // props of ScrollViewdataSource {this.state.dataSource}renderRow {r Text r.text /Text }/ );}55

import RefreshControl from 'react-native';import InfiniteScrollView from'react-native-infinite-scroll-view';// in JSX ListViewdataSource {.}renderRow {.}refreshControl { RefreshControl refreshing {this.state.refreshing}onRefresh {() . /* list posts */} / }rederScrollComponent {props InfiniteScrollView {.props} / }distanceToLoadMore {300}canLoadMore {this.state.hasMoreRows}onLoadMoreAsync {() . /* list more posts */}/ Refreshing & Scrolling56

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations57

// in app.jsimport {StackNavigator} from'react-navigation';const App StackNavigator({Home: {screen: HomeScreen},Contact: {screen: ContactScreen}});class HomeScreen extends React.Component {render() {const {navigate} this.props.navigation;return ( Button onPress {() navigate('Contact')} . /Button );}class ContactScreen extends React.Component {}render() {const {goBack} this.props.navigation;return ( Button onPress {() goBack()} . /Button );}}Navigation Supports Redux integration58

Outline Hello React Native––––––How it works?Components, props, and statesStylingEvent handlingImages and iconsData access WeatherMoodMobile– NativeBase– ScrollView and ListView– Navigation Animations59

People expect great UX from apps.So, animation is a “must”60

WeatherMoodMobile Checkout theparallax-headerbranch61

What does “parallax” mean?62

import {Animated, Easing} from 'react-native';class FadeInComponent extends React.Component {constructor(props) {.this.opacityAnim new Animated.value(0);}componentDidMount() {Animated.timing(this.opacityAnim, {toValue: 1,easing: Easing.back // or bounce, etc.duration: 1000 // in ms,useNativeDriver: true}).start();}render() {return ( Animated.View style {{opacity: this.opacityAnim}} . /Animated.View );}}Animations Or, try canned animations63

class FadeInComponent extends React.Component {constructor(props) {.this.state {opacity: 0};}componentDidMount() {this.fadeInId setTimeout(() {if (this.state.opacity 1.0)this.setState({opacity: this.state.opacity 0.0167});else clearTimeout(this.fadeInId);}, 16); // 60 fps}render() {return ( View style {{opacity: this.state.opacity}} . / );}}Why not use state?64

NativeUI (Main) ThreadNativeModules ThreadJS Thread Animated.timing()– Fires every frameTimer EventUpdate UIRun HandlerLayout65

NativeUI (Main) ThreadNativeModules ThreadJS Thread Transition of animated value is declarative– Known before start() Optimization:– High priority threads– Native driver allowing native-only animationTimer EventUpdate UIRun HandlerLayout66

componentDidMount() {Animated.timing(this.opacityAnim, {toValue: 1,.}).start();}render() {return ( Animated.View style {{opacity: this.opacityAnim, // fade intransform: [{translateY: this.opacityAnim.interpolate({ // slide ininputRange: [0, 1], // or [0, 0.5, 1],outputRange: [150, 0], // or [150, 50, 0]extrapolate: 'clamp' // or 'extend'})}]}} . /Animated.View );}Interpolation ofAnimated Values Also supports multiplesegments67

// in constructorthis.scrollAnim new Animated.Value(0);// in JSX ListView.onScroll {e {const y alue(y);}}Animated.event(/ [{nativeEvent:{contentOffset: {y: this.scrollAnim}}}],{useNativeDriver: true})Tracking Gestures Animated.Viewstyle {{opacity: this.scrollAnim.interpolate(inputRange: [0, 200],outputRange: [1, 0],extrapolate: 'clamp')}} . /Animated.View Declarative transition ofanimated value?68

Parallax HeadertranslateY Pitfall: the scroll viewitself is translating Fluctuate contentoffset (y)– y depends not only ongesturescrollAnim.interpolateonScroll {.offsetY} Solution: averagemultiple y's within asmall window69

Readings Official Guides RN internals– Android– iOS Awesome React Native70

Publishing Apple’s App Store:– Checklist Google Play Store:– Sign your APK first– Checklist71

Assignment Complete the “weather part” in Today.js Design and implement Forecast.js– Show forecast in the next few days– TODO list Put settings to the Settings screen– E.g., “location” for weather queries Once submission per group Bonus (up to 50%): creative animations72

React-Native Apps JS components render as native ones Learn once, write everywhere 13 Android Android SDKs Native UI JS Runtime React Native 3rd Party Libs NPM Pkgs (e.g., React) Bridge Your App Your App (JS) (Native UI & Modules) iOS iOS SDKs Native UI JS Runtime React Native 3 Party Libs NPM Pkgs (e

Related Documents:

May 02, 2018 · D. Program Evaluation ͟The organization has provided a description of the framework for how each program will be evaluated. The framework should include all the elements below: ͟The evaluation methods are cost-effective for the organization ͟Quantitative and qualitative data is being collected (at Basics tier, data collection must have begun)

Silat is a combative art of self-defense and survival rooted from Matay archipelago. It was traced at thé early of Langkasuka Kingdom (2nd century CE) till thé reign of Melaka (Malaysia) Sultanate era (13th century). Silat has now evolved to become part of social culture and tradition with thé appearance of a fine physical and spiritual .

On an exceptional basis, Member States may request UNESCO to provide thé candidates with access to thé platform so they can complète thé form by themselves. Thèse requests must be addressed to esd rize unesco. or by 15 A ril 2021 UNESCO will provide thé nomineewith accessto thé platform via their émail address.

̶The leading indicator of employee engagement is based on the quality of the relationship between employee and supervisor Empower your managers! ̶Help them understand the impact on the organization ̶Share important changes, plan options, tasks, and deadlines ̶Provide key messages and talking points ̶Prepare them to answer employee questions

Dr. Sunita Bharatwal** Dr. Pawan Garga*** Abstract Customer satisfaction is derived from thè functionalities and values, a product or Service can provide. The current study aims to segregate thè dimensions of ordine Service quality and gather insights on its impact on web shopping. The trends of purchases have

Chính Văn.- Còn đức Thế tôn thì tuệ giác cực kỳ trong sạch 8: hiện hành bất nhị 9, đạt đến vô tướng 10, đứng vào chỗ đứng của các đức Thế tôn 11, thể hiện tính bình đẳng của các Ngài, đến chỗ không còn chướng ngại 12, giáo pháp không thể khuynh đảo, tâm thức không bị cản trở, cái được

More than words-extreme You send me flying -amy winehouse Weather with you -crowded house Moving on and getting over- john mayer Something got me started . Uptown funk-bruno mars Here comes thé sun-the beatles The long And winding road .

Le genou de Lucy. Odile Jacob. 1999. Coppens Y. Pré-textes. L’homme préhistorique en morceaux. Eds Odile Jacob. 2011. Costentin J., Delaveau P. Café, thé, chocolat, les bons effets sur le cerveau et pour le corps. Editions Odile Jacob. 2010. Crawford M., Marsh D. The driving force : food in human evolution and the future.