Getting to React Native iOS developers using the tutorial

A. Native iOS integration projects React Native

  1. Create a new folder, such as RNProject, and then create a / ios sub-folders, copy the entire project into an existing iOS file.

  2. Create a file in RNProject package.json root directory, as follows:

{
  "name": "RNProject",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "yarn react-native start"
  }
}
  1. Open a terminal, cd to the project root directory, execute the following command React Native integrated modules:
$ yarn add react-native
  1. After one step on a waiting red notices box, it expressed the need to rely on the specified version react. We integrated the following command to react, note the version number of requirements need to strictly follow the prompts:
    Here Insert Picture Description
$ yarn add [email protected]

At this time, all are dependent on integrated under node_modules / directory, do git version control, should not upload all the files in this folder, but allow other collaborators also execute the above command to add dependencies. So should node_modules / directory record to .gitignore file.

  1. By cocoaPods the React Native integration into iOS project. By default you are already familiar with and installed cocoaPods. In the terminal, cd to / lower ios directory initialization cocoaPods:
$ pod init

Podfile open the file, edit the following:

# The target name is most likely the name of your project.
target 'RNProject' do

  # Your 'node_modules' directory is probably in the root of your project,
  # but if not, adjust the `:path` accordingly
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'CxxBridge', # Include this for RN >= 0.47
    'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
    'RCTText',
    'RCTImage',
    'RCTNetwork',
    'RCTWebSocket', # Needed for debugging
    'RCTAnimation', # Needed for FlatList and animations running on native UI thread
    # Add any other subspecs you want to use in your project
  ]
  # Explicitly include Yoga if you are using RN >= 0.42.0
  pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  # Third party deps podspec link
  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

end

Note target 'RNProject' do in the name of the iOS project, not the root directory name, but here in my root directory and iOS project names are RNProject.
After saving Podfile, execute the following command to start the installation:

$ pod install

So far, it has successfully integrated the existing RN iOS project, the project file is structured as follows:
Here Insert Picture Description

II. Native page jump RN

  1. Apple will block access to insecure HTTP link. We need to add Info.plist of iOS project:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

Here Insert Picture Description

  1. Creating index.js file in the root directory as a file React Native entrance on the iOS. And enter the following:
import React from 'react';
import {AppRegistry, StyleSheet, Text, View} from 'react-native';

class Hello extends React.Component {
  render() {
  	var {name} = this.props
    return (
      <View style={{flex: 1,justifyContent: 'center',alignItems: 'center'}}>
      	<Text>Hello {name}!</Text>
      </View>
    );
  }
}

AppRegistry.registerComponent('Hello', () => Hello);
  1. In Xcode, create a ViewController, and enter the following:
#import "ViewController.h"
#import <React/RCTRootView.h>

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
    button.center = self.view.center;
    [button setTitle:@"跳转RN" forState:0];
    [button setTitleColor:[UIColor greenColor] forState:0];
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)clickButton:(UIButton*)button{
    NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];
    
    RCTRootView *rootView =
    [[RCTRootView alloc] initWithBundleURL: jsCodeLocation
                                moduleName: @"Hello"
                         initialProperties: @{@"name":@"React Native"}
                             launchOptions: nil];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    [self presentViewController:vc animated:YES completion:nil];
}

@end

  1. Start RN Packager using the following command in the root directory
npm start
  1. After running in Xcode project, run after clicking "Go RN", both will jump to display Hello React Native RN achieved! Page:Here Insert Picture Description
    Here Insert Picture Description

III. Displayed watercress popular movies list

Each page should correspond to a separate js file, and in order to prevent the holding big project after the clear file structure, we created the following directories and files for the popular movie list: ./ src / page / HotMovie.js, in the HotMovie.js enter the following:

import React, {Component} from 'react';
import {StyleSheet, Image, Text, View, FlatList} from 'react-native';

var REQUEST_URL = "https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=20&page_start=0"

export default class HotMovie extends Component<Props> {

  constructor(props){
    super(props);
    this.state = {
      movies:null,
    }

    this.fetchData = this.fetchData.bind(this)
  }

  componentDidMount(){
    this.fetchData()
  }

  fetchData(){
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          movies:responseJson.subjects
        });
      })
  }

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


  renderLoadingView(){
    return (
      <View style={styles.container}>
        <Text>
          正在加载...
        </Text>
      </View>
    )
  }


  renderMovie({item}){
    return(
      <View style={styles.item}>
        <Image source={{url:item.cover}} style={styles.thumbnail}/>
        <View style={styles.itemRight}>
          <Text>{item.title}</Text>
          <Text>{item.rate}</Text>
        </View>
      </View>
    )
  }


}

const styles = StyleSheet.create({
  container: {
    flex:1,
    flexDirection:'row',
    alignItems:'center',
    justifyContent: 'center',
    alignItems: 'center',
  },
  item:{
    marginTop:1,
    flexDirection:'row',
    alignItems:'center',
    justifyContent: 'center',
    height:100,
    backgroundColor:'lightgray'
  },
  thumbnail:{
    width:53,
    height:81,
    backgroundColor:'lightgray'
  },
  itemRight:{
    flex:1,
    height:100,
    justifyContent: 'center',
    alignItems:'center'
  },
  list: {
    paddingTop: 50,
    backgroundColor: "#F5FCFF"
  }
});

2, the index.js modified as follows:

import React from 'react';
import {AppRegistry, StyleSheet, Text, View} from 'react-native';
import HotMovie from './src/page/HotMovie';

AppRegistry.registerComponent('HotMovie', () => HotMovie);

3, the primary button click event with the following:

- (void)clickButton:(UIButton*)button{
    NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];
    
    RCTRootView *rootView =
    [[RCTRootView alloc] initWithBundleURL: jsCodeLocation
                                moduleName: @"HotMovie"
                         initialProperties: nil
                             launchOptions: nil];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    [self presentViewController:vc animated:YES completion:nil];
}

3, FIG effect after operation:
Here Insert Picture Description

IV. Changed navigation

Length little long friends, opened with a continued https://blog.csdn.net/dolacmeng/article/details/90414040

V. Complete source code

Stamp https://github.com/dolacmeng/RNProject/tree/master

Published 103 original articles · won praise 55 · views 380 000 +

Guess you like

Origin blog.csdn.net/dolacmeng/article/details/90371964