Look at the demo

Write it up front

It has been about two Sundays since I started studying RN. Here I will record it for a brief summary. At present, RN’s strengths and weaknesses are clear;

  • advantage
    • RN is mixed development of a piece of code for multiple uses
    • The code is similar to the front end, and the Web transfer to RN is relatively easy
  • disadvantage
    • RN components are maintained by multiple third parties, and updates are uncontrollable, which may lead to more incompatibilities
    • Random combination of craters based on RN, component, and Xcode versions (this is annoying, and I spend most of my time doing this)
    • Multi-terminal compatibility and adaptation cost is large, and it will become more difficult with the scale of the project. To a certain extent, the development cost will be higher than that of the original. For example, Airbnb announced to give up using RN and return to the original technology

The body of the

1 Environment Installation

The official website is very detailed, according to the steps of the official website is basically no problem, I will not repeat

Website address: reactnative. Cn/docs/gettin…

2 familiar with RN

Create the Q project and run it in the iOS emulator

 react-native init q
 cd q
 react-native run-ios
Copy the code

The project contents are as follows:

  • Android: Android project file
  • Ios: ios engineering files
  • Node_modules: Directory for storing the react-native component dependencies
  • Package. json: depends on configuration JSON, similar to “Podfile” in cocoPods
  • Index.js: Project entry…

See first index. Js, the import is the introduction of files, AppRegistry. RegisterComponent (appName, () = > App); The whole idea is to register the project directory app.js as a component and import it, so that the initial display is the contents of app.js

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

Copy the code

The app.js file can be roughly divided into three parts

  • The introduction of the component
  • To build the UI
  • style

Those who have experience in front-end development are familiar with View, Text and ScrollView. In React-Native, all components need to be introduced separately. Please refer to the official documentation for all components and their functions

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
} from 'react-native';

import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';

Copy the code

Part of what we’re doing here is drawing UI, which is basically the same as HTML, with a bunch of components. Learning web or applets looks easy, but if not, it is recommended to learn the most basic HTML + CSS

const App: () => React$Node= () = > {return (
      <StatusBar barStyle="dark-content"/> <SafeAreaView> <ScrollView ..... . </SafeAreaView> </> ); };export default App;
Copy the code

Here are various styles, most of which use CSS. Seeing this, I might feel that React-Native is actually a shell of the previous code. It should be easy for those who have the previous knowledge to learn

const styles = StyleSheet.create({ scrollView: { backgroundColor: Colors.lighter, }, ..... . });Copy the code

Three attempts to Demo

With that in mind, try making a simple list page

1. Import components. The required components probably include these, especially FlatList components

import React, { Component } from "react";

import { Image, FlatList, StyleSheet, Text, View } from "react-native";
Copy the code

2. Export the default class App extension component, including other code below

export default class App extends Component {
}
Copy the code

3. Create a data array of length 8 and then assign the FlatList value

constructor(props) {
    super(props);
    this.state = {
      data: [{}, {}, {}, {}, {}, {}, {}, {}],
    };
}
Copy the code

4.RN’s render() function is actually similar to iOS’s ViewDidLoad() function in that it returns the specific content, which is fixed and can only be a component. Here I return the FlatList, and the fields are described below

  • Data: We need to give an array whose length corresponds to the list item
  • Style: List style
  • RenderItem: renderItem, here is the direct callrenderMovieApply colours to a drawing
  • KeyExtractor: Sets a unique key for each item, similar to an index
render() {
    return (
      <FlatList
        data={this.state.data}
        style={styles.list}
        renderItem={this.renderMovie.bind(this)}  
        keyExtractor={item => item.id}
      />
    );
 }
Copy the code

5. Use renderMovie to return the contents of the item

renderMovie({ item }) {
    return (
        <View style={styles.container}>
          <Image
            source={{ uri: 'https://gss3.bdstatic.com/7Po3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign=e4d6ea2325dda3cc0be4bf2639d25e3c/b6454 3a98226cffcb1f7cc0eb2014a90f703eaa9.jpg'}} style={styles.thumbnail} /> <View style={styles.rightContainer}> <View style={styles.titleWithout}> <Text Style ={styles.title}> </Text> <Text style={styles.tip}> </Text> </View> <Text style={styles.score}> <Text Style ={styles.grade}> 9.8 </Text></Text> <Text style={styles. </Text> <Text style={styles.cinema}> </Text> </View> </Text style={styles.buy}> </Text> </View>) }Copy the code

6. Finally, style. In fact, these can be played at will

Such a simple page is completed, the complete code is as follows, you can directly copy to replace the original content to run to see the effect

import React, { Component } from "react";

import { Image, FlatList, StyleSheet, Text, View, TouchableOpacity } from "react-native";


export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      data: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {},],
    };
  }

  render() {
    return (
      <FlatList
        data={this.state.data}
        style={styles.list}
        renderItem={this.renderMovie.bind(this)}  
        keyExtractor={item => item.id}
      />
    );
  }

  renderMovie({ item }) {
    return (
        <View style={styles.container}>
          <Image
            source={{ uri: 'https://gss3.bdstatic.com/7Po3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign=e4d6ea2325dda3cc0be4bf2639d25e3c/b6454 3a98226cffcb1f7cc0eb2014a90f703eaa9.jpg'}} style={styles.thumbnail} /> <View style={styles.rightContainer}> <View style={styles.titleWithout}> <Text Style ={styles.title}> </Text> <Text style={styles.tip}> </Text> </View> <Text style={styles.score}> <Text Style ={styles.grade}> 9.8 </Text></Text> <Text style={styles. </Text> <Text style={styles.cinema}> </Text> </View> </Text style={styles.buy}> </Text> </View>) } } var styles = StyleSheet.create({ container: { flex: 1, flexDirection:"row",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#fff"
  },
  header: {
    height: 20,
    marginTop: 44,
  },
  rightContainer: {
    flex: 1,
    paddingLeft: 18,
  },
  titleWithout: {
    flexDirection: "row",
    fontWeight: "bold",
    alignItems: "center",
  },
  title: {
    fontSize: 14,
    marginTop: 4,
    lineHeight: 0,
  },
  tip: {
    backgroundColor: "# 999",
    fontSize: 8,
    textAlign: "center",
    color: "#fff",
    height: 14,
    width: 40,
    lineHeight: 14,
    borderRadius: 2,
    marginLeft: 4,
    marginTop: 4,
  },
  score: {
    paddingTop: 8,
    fontSize: 12,
    color: "# 666",
  },
  starring: {
    paddingTop: 4,
    fontSize: 12,
    color: "# 666",
  },
  cinema: {
    paddingTop: 4,
    fontSize: 12,
    color: "# 666",
  },
  buy: {
    fontSize: 12,
    // color:'# 333',
    width: 46,
    height: 24,
    lineHeight: 24,
    textAlign: "center",
    backgroundColor: "#D44145",
    color: "#fff",
    borderRadius: 12,
    marginRight: 20,

  },
  grade: {
    color: "#DF8D7A",
  },
  year: {
    textAlign: "center"
  },
  thumbnail: {
    width: 68,
    height: 94,
    marginLeft: 20,
    marginTop: 10,
    marginBottom: 10,

  },
  list: {
    paddingTop:40,
    backgroundColor: "#F5FCFF"
  },
  headerOutline: {
    backgroundColor: "#fff",
    marginTop: 44,
  },
  headerInside: {
    backgroundColor: "#f5f5f5",
    flexDirection: "row",
    justifyContent: 'space-between',
    marginLeft: 20,
    marginRight: 20,
    marginBottom: 6,
    paddingTop: 10,
    paddingBottom: 4,
    paddingLeft: 10,
    paddingRight: 10,
  },
  trendIcon: {
    width: 10,
    height: 14,
    marginLeft: 10,
    marginTop: -1,
  },
  trendText: {
    height: 22,
    color: '# 333',
    fontWeight: "bold",
  },
  trendR: {
    color: '# 333',
    fontSize: 10,
    fontWeight: "bold",
    height: 22,
  },
  trendRText: {

  },
  trendMoney: {
    color: '#D24349',}});Copy the code

Two Navigation and the Tabbar

As shown in the figure, the ultimate goal is to create a demo with Navigation and Tabbar, which can be divided into three steps

  1. Installation of components
  2. Create two root pages and a detail page on tabbar
  3. Modify theindex.jsThe entrance

1. Install the React-Navigation component

Note: There is a hole in the react-Navigation 4, which is very different from the react-Navigation 3. Now the tutorial on the Internet basically uses the React-Navigation 3

Yarn add [email protected] yarn add react-native- mouth-handlerCopy the code

You might get this error here


Error: Requiring unknown module "447". If you are sure the module exists, try restarting Metro. You may also want to run `yarn` or `npm install`.

Copy the code

There are many reasons for this error, you can try

npm install
react-native run-ios
Copy the code

or

cd ios
pod install
cd. react-native run-iosCopy the code

2. To createdetailsScreen.js.settingScreen.js.navigation.jsfile

DetailsScreen. Js content

import React from 'react';
import {
    View,
    Text,
    Button,
    Image,
} from 'react-native';

export default class detailsScreen extends React.Component {

   
    render() {
        return (
            <View style={{flex:1, alignItems:'center',justifyContent: 'center'}}><Text> details </Text></View>); }}Copy the code

SettingScreen. Js content

import React from 'react';
import {
    View,
    Text,
    Button,
    Image,
} from 'react-native';

export default class settingScreen extends React.Component {

   
    render() {
        return (
            <View style={{flex:1, alignItems:'center',justifyContent: 'center'}}><Text> Settings page </Text></View>); }}Copy the code

The navigation. Js content needs to be explained step by step, first introducing all the required components and pages

import React from 'react';
import { Text } from 'react-native'

import HomeScreen from "./App";        
import DetailsScreen from "./detailScreen";
import SettingScreen from "./settingScreen";

import {
    createStackNavigator,
    createAppContainer,
    createBottomTabNavigator
} from 'react-navigation';

Copy the code

Here we declare HomeStack and SettingsStack;

CreateStackNavigator provides the ability to switch between APP screens in the form of a stack and also manages switching between screens, with newly switched screens placed at the top of the stack.

const HomeStack = createStackNavigator({
    Home: { screen: HomeScreen, }
})
const SettingsStack = createStackNavigator({
    Settings: { screen: SettingScreen },
})

Copy the code

Here we declare the TabNavigator

Bottomtab navigator (RouteConfigs, BottomTabNavigatorConfig) is equivalent to the TabBarController in iOS, the TAB bar at the bottom of the screen

  • RouteConfigs(Mandatory) : The route configuration object is a mapping from the route name to the route configuration, telling the navigator what to render for the route.
  • BottomTabNavigatorConfig(optional) : configure the navigator’s routing style (e.g., default first screen, navigationOptions, paths, etc.) (e.g., transition mode, header mode, etc.).
const TabNavigator = createBottomTabNavigator(
    {
      Home: { screen: HomeStack },
      Settings: { screen: SettingsStack }
    },
    {
      navigationOptions: () => ({
        header: null
      }),
      defaultNavigationOptions: ({ navigation }) => ({
        tabBarLabel: ({ tintColor}) => {
          const { routeName } = navigation.state
          switch (routeName) {
            case 'Home':
              return <Text style={{ color: tintColor, fontSize: 12 }}>{'home'}</Text>
            case 'Settings':
              return <Text style={{ color: tintColor, fontSize: 12 }}>{'set'}</Text>
          }
        },
        tabBarIcon: ({ focused, tintColor }) => {
            let urld 
            const { routeName } = navigation.state
            switch (routeName) {
                case 'Home':
                    return <Image source={{ uri: 'https://static.easyicon.net/preview/119/1191814.gif' }} style={[{height: 20, width: 20}]}/>    
                case 'Settings':
                    return <Image source={{ uri: 'https://static.easyicon.net/preview/121/1215319.gif' }} style={[{height: 20, width: 20}]}/>    
            }
        }
      }),
      tabBarOptions: {
        inactiveTintColor: 'gray',}})Copy the code

Finally, the route is set and returned

const AppStack = createStackNavigator({
    Tabs: TabNavigator,
    Details: { screen: DetailsScreen },
  }, {
    defaultNavigationOptions: () => ({
    })
  })
export default createAppContainer(AppStack)

Copy the code

The complete code is as follows

import React from 'react';
import { Text,Image} from 'react-native'

import HomeScreen from "./App";     
import DetailsScreen from "./detailScreen";
import SettingScreen from "./settingScreen";

import {
    createStackNavigator,
    createAppContainer,
    createBottomTabNavigator
} from 'react-navigation';

const HomeStack = createStackNavigator({
    Home: { screen: HomeScreen, }
})
const SettingsStack = createStackNavigator({
    Settings: { screen: SettingScreen },
})

const TabNavigator = createBottomTabNavigator(
    {
      Home: { screen: HomeStack },
      Settings: { screen: SettingsStack }
    },
    {
      navigationOptions: () => ({
        header: null
      }),
      defaultNavigationOptions: ({ navigation }) => ({
        tabBarLabel: ({ tintColor}) => {
          const { routeName } = navigation.state
          switch (routeName) {
            case 'Home':
              return <Text style={{ color: tintColor, fontSize: 12 }}>{'home'}</Text>
            case 'Settings':
              return <Text style={{ color: tintColor, fontSize: 12 }}>{'set'}</Text>
          }
        },
        tabBarIcon: ({ focused, tintColor }) => {
            let urld 
            const { routeName } = navigation.state
            switch (routeName) {
                case 'Home':
                    return <Image source={{ uri: 'https://static.easyicon.net/preview/119/1191814.gif' }} style={[{height: 20, width: 20}]}/>    
                case 'Settings':
                    return <Image source={{ uri: 'https://static.easyicon.net/preview/121/1215319.gif' }} style={[{height: 20, width: 20}]}/>    
            }
        }
      }),
      tabBarOptions: {
        inactiveTintColor: 'gray',
      }
    }
)

const AppStack = createStackNavigator({
    Tabs: TabNavigator,
    Details:DetailsScreen,
  }, {
    defaultNavigationOptions: () => ({
    })
  })


export default createAppContainer(AppStack)


Copy the code

3. Modifyindex.jsThe entrance

This simply changes the entry to navigation.js

import {AppRegistry} from 'react-native';
import Nav from './navigation.js';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => Nav);

Copy the code

Save it and you can see that the shelf of the App is basically formed

The next step is to set up click events so the demo can jump

First go back to the app. js page and set the navigation bar title on the home page

static navigationOptions = ({ navigation }) => { const { params = {} } = navigation.state const onPressRightButtonFunc =  params.openPublisher ||function() {}return {
      title: 'home',}}Copy the code

Introduces the TouchableOpacity setting click event

import {  TouchableOpacity } from "react-native"; . . renderMovie({ item }) { const navigate = this.props.navigation;return(<TouchableOpacity activeOpacity={0.5} onPress={() => navigate. Navigate ('Details'> / /)}'Details'It was declared in navigation. Js earlier... // Here is the UI code for the previous item </TouchableOpacity>Copy the code

Up to here basically has completed this demo, the rest are some repetitive UI work also do not repeat, this is slightly optimized code and detail page, can not understand according to the source code to.

Here my source code is the basic components are good, download can run, because the larger first upload to Baidu cloud.

Link: pan.baidu.com/s/1854tyx1R… Extraction code: KGMB

Other online demos are unfriendly to newcomers, requiring various components to be installed and run again. Various errors are easy to discourage newcomers

Afterword.

The original intention is to let the novice quickly start to make a demo, later found that still need a little web experience, the content is a little too much, said not so detailed place please forgive me. We will keep updating this demo;

If you find this article helpful, please pay attention to it