Slide 1

Slide 1 text

How to React Native

Slide 2

Slide 2 text

Дмитрий Ульянов JavaScript Developer linkedin.com/in/drukas16

Slide 3

Slide 3 text

2 проекта 10 месяцев 2-3 JS разработчика 1 нативный разработчик

Slide 4

Slide 4 text

Кто использует React Native?

Slide 5

Slide 5 text

React

Slide 6

Slide 6 text

Чем хорош React?

Slide 7

Slide 7 text

Декларативность Компонентный подход One way data flow Virtual DOM

Slide 8

Slide 8 text

React - это reconciler

Slide 9

Slide 9 text

ReactDOM - это renderer

Slide 10

Slide 10 text

React Native - тоже renderer

Slide 11

Slide 11 text

JS Native Bridge

Slide 12

Slide 12 text

JS Движок JavaScript Core. Babel под капотом и свой react-native пресет Поддержка ES6 и ES7 фич Полифиллы для ES6-ES7 методов Object, Array и String; а также для XMLHttpRequest, fetch, консоли, тайм-аутов и тд.

Slide 13

Slide 13 text

Быстрый старт

Slide 14

Slide 14 text

Create React Native App expo.io

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

Компоненты и стили

Slide 17

Slide 17 text

components/text/styles.js import { StyleSheet } from 'react-native' import * as Styles from '@styles' export default StyleSheet.create({ default: { fontSize: Styles.fontSizes.normal, fontFamily: Styles.fonts.primaryFont, color: Styles.colors.dark, }, bold: { fontWeight: ‘bold’ }, "/* other styles "*/ })

Slide 18

Slide 18 text

import { create } from ‘react-native-platform-stylesheet' export default create({ default: { fontSize: 18, ios: { fontFamily: 'Helvetica' }, android: { fontFamily: 'Roboto' } } }) components/text/styles.js, платформозависимый код

Slide 19

Slide 19 text

import { create } from ‘react-native-platform-stylesheet' export default create({ default: { fontSize: 18, ios: { fontFamily: 'Helvetica' }, android: { fontFamily: 'Roboto' } } }) components/text/styles.js, платформозависимый код

Slide 20

Slide 20 text

{ "/* ""... "*/ "rnpm": { "assets": [ "fonts" ] } } Кладем свои шрифты в fonts/ и обновляем package.json $ react-native link assets

Slide 21

Slide 21 text

import styles from './styles.js' const Text = ({children, ""...props}) !=> { const { bold, color, style: styleExtension, ""...otherProps } = props const style = [ styles.default, styleExtension, bold !&& styles.bold, color !&& { color }, ] return ( {children} " ) } components/text/index.js, теперь со стилями

Slide 22

Slide 22 text

import styles from './styles.js' const Text = ({children, ""...props}) !=> { const { bold, color, style: styleExtension, ""...otherProps } = props const style = [ styles.default, styleExtension, bold !&& styles.bold, color !&& { color }, ] return ( {children} " ) } components/text/index.js, теперь со стилями

Slide 23

Slide 23 text

Использование компонента Text Default text!" Bold text!" Colored text! " "

Slide 24

Slide 24 text

Использование компонента Text Default text!" Bold text!" Colored text! " "

Slide 25

Slide 25 text

import Color from 'color' const teal = Color('teal') const gray = Color('dimgray') const darker = color !=> color.darken(0.25) const withOpacity = color !=> color.alpha(0.8) export default { dark: gray, darker: darker(gray), primary: teal, primaryWithOpacity: withOpacity(teal), } styles/colors.js, используем npm модуль color

Slide 26

Slide 26 text

Платформозависимый код const OS = Platform.OS "// 'android' or 'ios' const platform = Platform.select({ ios: 'ios', android: 'android' }) ├── filename.js "// кросплатформенный файл ├── filename.ios.js "// iOS └── filename.android.js "// Android

Slide 27

Slide 27 text

Готовые компоненты

Slide 28

Slide 28 text

NativeBase

Slide 29

Slide 29 text

• MRN • React Native Material Design • React Native Material Kit

Slide 30

Slide 30 text

Анимации

Slide 31

Slide 31 text

Animated API LayoutAnimation API class SpinningImage extends React.Component { spinValue = new Animated.Value(0) componentDidMount() { this.spin() } spin = () => { this.spinValue.setValue(0) Animated.timing(this.spinValue, { toValue: 1, duration: 2000, easing: Easing.linear, useNativeDriver: true, }).start(this.spin) } render() { const spin = this.spinValue.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '360deg'] }) const transform = [{rotate: spin}] const style = [styles.image, {transform}] return ( ) } } if (Platform.OS === 'android') { UIManager.setLayoutAnimationEnabledExperimental(true); } class BoxWithSizeChanges extends React.Component { state = {size: 200} increaseSize = () => { LayoutAnimation.spring() // OR LayoutAnimation.configureNext(CUSTOM_CONFIG) this.setState(state => ({size: state.size + 50})) } render() { const {size} = this.state const sizes = {height: size, width: size} const style = [styles.box, sizes] return ( ) } }

Slide 32

Slide 32 text

Animated API LayoutAnimation API

Slide 33

Slide 33 text

Real World React Native Animations

Slide 34

Slide 34 text

oblador/react-native-animatable Up and down you go ❤

Slide 35

Slide 35 text

Навигация

Slide 36

Slide 36 text

React Native решения “из коробки” NavigatorIOS Navigator NavigationExperimental

Slide 37

Slide 37 text

React Native решения “из коробки” NavigatorIOS Navigator NavigationExperimental

Slide 38

Slide 38 text

Комьюнити решения native-navigation ex-navigation react-native-navigation react-navigation react-native-redux-router react-native-router-redux react-native-route-navigator react-native-simple-router react-native-router react-native-router-flux react-router-navigation

Slide 39

Slide 39 text

react-community/react-navigation wix/react-native-navigation aksonov/react-native-router-flux

Slide 40

Slide 40 text

react-native-router-flux

Slide 41

Slide 41 text

Примеры, компоненты Router & Scene {"/* Nested scenes "*/} " " "

Slide 42

Slide 42 text

Примеры, использование Actions {"/* Nested scenes "*/} " " " class About extends React.Component { goHome = () "=> Actions['home']() popHome = () "=> Actions.pop() goHomeWithParams = () "=> Actions['home']({ iWillBeAvailableThroughPropsAtHome: ‘Hi there!’ }) "/* render etc "*/ }

Slide 43

Slide 43 text

Примеры, вспомогательные функции const createScene = (key, {title, ""...props}) "=> } title={(title "|| key).toUpperCase()} {""...props} "/> const Scenes = ( {createScene('home', {component: Home, initial: true})} {createScene('about', {component: About})} {createScene('logout', {component: Logout, title: 'Log Out'})} " " )

Slide 44

Slide 44 text

Примеры, Drawer import Drawer from 'react-native-drawer' import { DefaultRenderer, Keyboard } from 'react-native-router-flux' "/* Drawer render "*/ const {navigationState, onNavigate} = props return ( } onOpenStart={Keyboard.dismissKeyboard}> " )

Slide 45

Slide 45 text

Примеры, Sub-scenes const ProfileScenes = ( " ) Примеры, Switch ({session: getSession(state)}))(Switch)} selector={props "=> props.session ? 'main' : 'unauthorized'} > "

Slide 46

Slide 46 text

react-navigation

Slide 47

Slide 47 text

Примеры, StackNavigator StackNavigator({ Home: { screen: HomeScreen, navigationOptions: ({navigation}) "=> ({ title: 'Home', headerRight: , header: "/* other screen props "*/ }) }, About, "/* other screens "*/ }, { headerMode: 'float', initialRouteName: 'Home' "/* other StackNavigator props "*/ })

Slide 48

Slide 48 text

Примеры, TabNavigator TabNavigator({ Home: { screen: HomeScreen, navigationOptions: ({navigation}) "=> ({ tabBarLabel: 'Home', tabBarIcon: ({tintColor}) "=> }) }, Feed, "/* other tabs "*/ }, { tabBarComponent: TabBarBottom, tabBarOptions: { activeTintColor: 'teal', "/* other tabBar props "*/ }, "/* other TabNavigator props "*/ })

Slide 49

Slide 49 text

Примеры, DrawerNavigator DrawerNavigator({ Home: { screen: HomeScreen, navigationOptions: ({navigation}) "=> ({ drawerLabel: 'Home', drawerIcon: ({tintColor}) "=> }) }, Profile, "/* other tabs "*/ }, { activeTintColor: 'teal', contentComponent: props "=> " "/* other DrawerNavigator props "*/ })

Slide 50

Slide 50 text

Примеры, nested navigators StackNavigator({ Tabs: { screen: TabNavigator({ "/* tabs "*/ }) }, Stack: { screen: StackNavigator({ "/* screens "*/ }) } })

Slide 51

Slide 51 text

Примеры, screen props this.props.navigation = { dispatch, goBack, navigate, "/* few more "*/ } NavigationActions NavigationActions.navigate({ routeName: 'Profile', actions: [ NavigationActions.navigate({ routeName: 'Friends', }) ] })

Slide 52

Slide 52 text

Работа с данными

Slide 53

Slide 53 text

Redux

Slide 54

Slide 54 text

Getting Started with Redux Building React Applications with Idiomatic Redux

Slide 55

Slide 55 text

Набор джентльмена redux && react-redux redux-logger / redux-devtools ducks modular structure redux-actions reselect redux-saga redux-persist

Slide 56

Slide 56 text

erikras/ducks-modular-redux import { createAction, handleActions } from 'redux-actions' import { moduleName } from './config' // moduleName = 'todosModule' const initialState = {todos: []} // MAY export action type, if it should be accessible // in other parts of the app (e.g. redux-saga or other module) const TODO_ADD = `${moduleName}/TODO_ADD` // MUST export creators export const addTodo = createAction(TODO_ADD) // MUST export reducer as default export default handleActions({ [TODO_ADD]: (state, {payload}) => ({todos: […state, payload]}) }, initialState); // selectors, sagas, epics etc. MAY also be named export redux/modules/todos/index.js

Slide 57

Slide 57 text

import { createSelector } from 'reselect' import { moduleName } from ‘./config' export const getTodos = state => state[moduleName].todos export const getVisibilityFilter = state => state[moduleName].filter export const getVisibleTodos = createSelector( [getTodos, getVisibilityFilter], (todos, visibilityFilter) => { switch (filter) { case 'SHOW_ALL': return todos case 'SHOW_COMPLETED': return todos.filter(todo => todo.completed) case 'SHOW_ACTIVE': return todos.filter(todo => !todo.completed) } } ) // todoList.js | import * as todosSelectors from '@modules/todos/selectors' redux/modules/todos/selectors.js reactjs/reselect

Slide 58

Slide 58 text

redux-thunk redux-loop redux-observable 5,402 1,214 2,992 8,129 Сайд-эффекты в Redux redux-saga

Slide 59

Slide 59 text

Redux-Thunk const a =
dispatch(actions.loadUser(userId)) }>{username}
export const loadUser = userId => async dispatch => { try { const user = await userService.load(userId) dispatch(userLoaded(user)) } catch (err) { dispatch(userLoadFailed(err)) } } const a =
dispatch(actions.userNameClicked(userId)) }>{username}
function * watchUserNameClickAndLoad () { yield * takeLatest(USER_NAME_CLICKED, loadUser) } function * loadUser ({payload}) { try { const user = yield call(userService.load, payload) yield put(userLoaded(user)) } catch (err) { yield put(userLoadFailed(err)) } }

Slide 60

Slide 60 text

Императивный flow + Декларативные сайд-эффекты + Мощь генераторов + Огромное кол-во хелперов

Slide 61

Slide 61 text

Хелперы / Эффекты • take (watcher) • takeLatest (cancels previous) • takeEvery • call (blocking) • fork (non-blocking) • put (saga dispatch) • select (saga mapState) • delay • cancel • race && all (like in Promises) etc.

Slide 62

Slide 62 text

redux-saga: login flow example function * authorization () { // Check the storage for cached token and profile let [token, profile] = yield [ call(auth.getToken), call(auth.getProfile), ] // so now user may be logged in... }

Slide 63

Slide 63 text

redux-saga: login flow example // ...or may not, so we gonna wait for it if (!token) { const {payload: credentials} = yield take(profileActions.SIGN_IN) const {response, error} = yield call(authRequest, credentials) if (error) { yield put(profileActions.signInFailed(error)) continue } token = response.token profile = response.profile yield [ call(auth.setToken, token), call(auth.setProfile, profile), ] }

Slide 64

Slide 64 text

redux-saga: login flow example // Now when we have token and profile // We can let user in yield put(profileActions.signInSuccess({token, profile})) yield take(profileActions.SIGN_OUT) token = profile = null yield [ call(auth.removeToken), call(auth.removeProfile), ] yield put(stackActions.clear()) yield put(profileActions.signOutSuccess())

Slide 65

Slide 65 text

redux-saga: login flow example function * authorization () { // Check the storage for cached token and profile let [token, profile] = yield [call(auth.getToken), call(auth.getProfile)] while (true) { if (!token) {…} /* Receive token and profile data */ yield put(profileActions.signInSuccess({token, profile})) yield take(profileActions.SIGN_OUT) /* Other signOut stuff */ } }

Slide 66

Slide 66 text

Ignite

Slide 67

Slide 67 text

https://infinite.red/ignite

Slide 68

Slide 68 text

Заходите на Medium

Slide 69

Slide 69 text

Twitter @reactjs @reactnative @dan_abramov @Vjeux @JI @grabbou @tylermcginnis33 @koltal

Slide 70

Slide 70 text

По максимуму используйте PropTypes и DefaultProps Для клавиатуры используйте KeyboardAvoidingView Внимательно изучайте документацию Не пренебрегайте селекторами Найдите в себе силы разобраться с Redux-Saga - не пожалеете Не забывайте убивать console.log, когда льете в прод И конечно же пишите на React Native - он крутой inline-советы напоследок

Slide 71

Slide 71 text

Вопросы? linkedin.com/in/drukas16