2019-04-07 14:16:06 qq_37021554 阅读数 275
  • 完全征服React Native

    React Native是Facebook于2015年推出的跨平台开发工具,可用于开发Android和iOS App,并且同时具有混合开发的优点(热更新,跨平台)以及本地App的性能。 本课程采用新的ES6开发,主要内容包括ReactNative的基础知识,ReactNative的布局,组件,API,封装本地API和组件,发布ReactNative App,本地与ReactNative深度结合

    57505 人正在学习 去看看 李宁

前置条件:

  1. 安装好react-native,通过 react-native init xxxproject
  2. 再react-native run-android运行
  3. 安装好react-navigation相关可以看官网的文档。

文件目录:

其中几个Page页面都只是页面对应字改了一下而已。

 

AppNavigator.js

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

import WelcomePage from '../pages/WelcomePage'
import DetailPage from '../pages/DetailPage'
import HomePage from '../pages/HomePage'

const MainNavigator = createStackNavigator({
  HomePage: {
    screen:HomePage,
    navigationOptions: {
      header: null
    }
  },
  DetailPage: {
    screen:DetailPage
  }
});
const InitNavigator = createStackNavigator({
   WelcomePage: {
    screen:WelcomePage,
    navigationOptions: {
      header: null
    }
  }
});

export default createAppContainer(createSwitchNavigator(
  {
    Init: InitNavigator,
    Main: MainNavigator,
  },
  {
    initialRouteName: 'Init',
  }
));

SwitchNavigator 的用途是一次只显示一个页面。 默认情况下,它不处理返回操作。我们可以通过它做一个一开始初始化欢迎页面,以及后续展示页面。

header:可以设置一些导航的属性,如果隐藏顶部导航栏只要将这个属性设置为null

 

welcomePage.js

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import NaivgationUtil from '../navigator/NavigationUtil';

type Props = {};
export default class WelcomePage extends Component <Props> {
    componentDidMount() {
        this.timer = setTimeout(() => {
            NaivgationUtil.resetToHomePage({
                navigation: this.props.navigation
            })
        }, 2000);
    }
    componentWillUnmount() {
        this.timer&&clearTimeout(this.timer);
    }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>WelcomePage</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

通过挂载定时器来定时跳转,同时记得销毁定时器。

NaivgationUtil.js 

作为一个util文件 需要的公共方法的提取

export default class NaivgationUtil {
    static goPage(params, page) {
        const navigation  = NaivgationUtil.navigation;
        if(!navigation) {
            console.log('navigation can not be null')
            return;
        }
        navigation.navigate(
            page,
            {
                ...params
            }
        )
    }
    static goBack(navigation) {
        navigation.goback();
    }
    static resetToHomePage(params) {
        const { navigation } = params;
        navigation.navigate('Main');
    }
};

同时需要将index.js入口文件进行修改一下

/**
 * @format
 */

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

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

接着需要一个顶部的tab

tab.js

tab中引入了需要的页面.

icons用了react-native-vector-icons 里面的三个类。安装react-native-vectors-icons 除了npm 以外还需要react-native link react-native-vector-icons 来进行自动关联。

方法较为类似,有screen对应页面,以及options对应的其他选项的配置,包含标题,icon。

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

import FavoritePage from './FavoritePage';
import MyPage from './MyPage';
import PopularPage from './PopularPage';
import TrendingPage from './TrendingPage';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import Ionicons from 'react-native-vector-icons/Ionicons';
import FontAwesome from 'react-native-vector-icons/FontAwesome';

const TabNavigator = createBottomTabNavigator({
    FavoritePage: {
        screen: FavoritePage,
        navigationOptions: {
            tabBarLabel: "收藏",
            tabBarIcon: ({tintColor, focused}) => (
                <MaterialIcons
                    name={'favorite'}
                    size={26}
                    style={{color: tintColor}}
                />
            )
        }
    },
    MyPage: {
        screen: MyPage,
        navigationOptions: {
            tabBarLabel: "我的",
            tabBarIcon: ({tintColor, focused}) => (
                <FontAwesome
                    name={'user'}
                    size={26}
                    style={{color: tintColor}}
                />
            )
        }        
    },
    PopularPage: {
        screen: PopularPage,
        navigationOptions: {
            tabBarLabel: "最热",
            tabBarIcon: ({tintColor, focused}) => (
                <MaterialIcons
                    name={'whatshot'}
                    size={26}
                    style={{color: tintColor}}
                />
            )
        }
    },
    TrendingPage: {
        screen: TrendingPage,
        navigationOptions: {
            tabBarLabel: "趋势",
            tabBarIcon: ({tintColor, focused}) => (
                <Ionicons
                    name={'md-trending-up'}
                    size={26}
                    style={{color: tintColor}}
                />
            )
        }   
    },
});

export default createAppContainer(TabNavigator);

 top.js

同样和底部较为类似。


import {
    createMaterialTopTabNavigator, createAppContainer
} from 'react-navigation';

import Tab1 from './Tab1';
import Tab2 from './Tab2';
const TabNavigator = createMaterialTopTabNavigator({
    PopularTab1: {
        screen: Tab1,
        navigationOptions: {
            tabBarLabel: "tab1"
        }
    },
    PopularTab2: {
        screen: Tab2,
        navigationOptions: {
            tabBarLabel: "tab2"
        }
    }
});

export default createAppContainer(TabNavigator);

最后还有一个详情页面的跳转:

tab1.js

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

type Props = {};
import NavigatorUtil from '../navigator/NavigationUtil'
export default class Tab1 extends Component <Props> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>PopularPage1</Text>
        <Text onPress={() => {
            NavigatorUtil.goPage({
                navigation: this.props.navigation
            }, "DetailPage")
        }}>跳转到详情页</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

 

结果显示:

demo下载:

https://download.csdn.net/download/qq_37021554/11094521 

2016-06-03 17:02:10 totogo2010 阅读数 4650
  • 完全征服React Native

    React Native是Facebook于2015年推出的跨平台开发工具,可用于开发Android和iOS App,并且同时具有混合开发的优点(热更新,跨平台)以及本地App的性能。 本课程采用新的ES6开发,主要内容包括ReactNative的基础知识,ReactNative的布局,组件,API,封装本地API和组件,发布ReactNative App,本地与ReactNative深度结合

    57505 人正在学习 去看看 李宁

在Demo主要是展示一个电影信息和在ListView展示25个电影信息。

1、初始化一个项目并运行

打开终端,输入:

react-native init DemoProject

输入后初始化一个项目返回信息如下:
有时候Installing react-native package from npm…
这一步会很慢,耐心等待,没问题的。

init DemoProject
This will walk you through creating a new React Native project in /Users/iOSDev_szzc/Downloads/DemoProject
Installing react-native package from npm...
Setting up new React Native app in /Users/iOSDev_szzc/Downloads/DemoProject
react@15.0.2 node_modules/react
├── object-assign@4.1.0
├── loose-envify@1.2.0 (js-tokens@1.0.3)
└── fbjs@0.8.3 (immutable@3.8.1, ua-parser-js@0.7.10, promise@7.1.1, isomorphic-fetch@2.2.1, core-js@1.2.6)
To run your app on iOS:
   cd /Users/iOSDev_szzc/Downloads/DemoProject
   react-native run-ios
   - or -
   Open /Users/iOSDev_szzc/Downloads/DemoProject/ios/DemoProject.xcodeproj in Xcode
   Hit the Run button
To run your app on Android:
   Have an Android emulator running (quickest way to get started), or a device connected
   cd /Users/iOSDev_szzc/Downloads/DemoProject
   react-native run-android

初始化成功,cd到DemoProject目录,运行

react-native run-ios

这个运行的大概原理就是用脚本编译并打开模拟器运行,模拟器打开后大概是这样的:

这证明你第一个react native项目运行成了。

2、显示一个电影描述

在项目中打开index.ios.js文件,复制下面代码,覆盖原来的代码,保存。然后在模拟器按下 Cmd+R,就能看到效果了。

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

var MOCKED_MOVIES_DATA = [
    {title: '爱丽丝梦游仙境2', year: '2016', posters: {thumbnail: 'http://pic.spider.com.cn/pic//filmpic/jdt/1462936153362_mobile2.jpg'}},
];

class DemoProject extends Component
{
    render() {
        var movie = MOCKED_MOVIES_DATA[0];
        return (
            <View style={styles.container}>
                <Text>{movie.title}</Text>
                <Text>{movie.year}</Text>
                <Image
                    source={{uri: movie.posters.thumbnail}}
                    style={styles.thumbnail}
                />
            </View>
        );
    }

};

var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    thumbnail: {
        width: 53,
        height: 81,
    },
});
AppRegistry.registerComponent('DemoProject', () => DemoProject);

1.import

这里有两个import,分别是from react和react-native
react和react-native是两个东西,大家先有个概念.大概的区别,其他地方找了一个比较靠谱的解释:

ReactJs和React Native的原理是相同的,都是由js实现的虚拟dom来驱动界面view层渲染。
ReactJs是驱动html dom渲染; React Native是驱动android/ios原生组件渲染。
React 和 React Native的区别
这里写图片描述

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

2.模拟数据

相当于一个全局变量

var MOCKED_MOVIES_DATA = [
    {title: '爱丽丝梦游仙境2', year: '2016', posters: {thumbnail: 'http://pic.spider.com.cn/pic//filmpic/jdt/1462936153362_mobile2.jpg'}},
];

3.组件渲染

DemoProject相当于一个组件

class DemoProject extends Component
{
    render() {
        var movie = MOCKED_MOVIES_DATA[0];
        return (
            <View style={styles.container}>
                <Text>{movie.title}</Text>
                <Text>{movie.year}</Text>
                <Image
                    source={{uri: movie.posters.thumbnail}}
                    style={styles.thumbnail}
                />
            </View>
        );
    }

};

4.样式

定义组件和组件内控件的样式,

var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    thumbnail: {
        width: 53,
        height: 81,
    },
});

5.注册组件为程序入口

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

修改样式

改成下面这样的布局

+---------------------------------+
|+-------++----------------------+|
||       ||        Title         ||
|| Image ||                      ||
||       ||        Year          ||
|+-------++----------------------+|
+---------------------------------+

增加三个样式和修改container的样式

container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
 rightContainer: {
    flex: 1,
  },
  title: {
    fontSize: 20,
    marginBottom: 8,
    textAlign: 'center',
  },
  year: {
    textAlign: 'center',
  },

把return内容改为如下:

 return (
        <View style={styles.container}>
          <Image
            source={{uri: movie.posters.thumbnail}}
            style={styles.thumbnail}
          />
          <View style={styles.rightContainer}>
            <Text style={styles.title}>{movie.title}</Text>
            <Text style={styles.year}>{movie.year}</Text>
          </View>
        </View>
      );

Cmd+R刷新,效果如下

这个相当于给react native运行的web server端,不能关闭,如果关闭会模拟器提示 Could not connect to development server的。
如果不小心关闭了,运行这个命令可以启动

npm start

这里写图片描述

先写到这,一篇太长的话,会让人缺乏看下去的勇气。
这骗其实就是官网教程的一个简版和细化我认为比好的细节的版本。喜欢的同学可以直接访问官网学习:
http://facebook.github.io/react-native/docs/tutorial.html

2017-08-18 11:11:09 xkc_0706 阅读数 535
  • 完全征服React Native

    React Native是Facebook于2015年推出的跨平台开发工具,可用于开发Android和iOS App,并且同时具有混合开发的优点(热更新,跨平台)以及本地App的性能。 本课程采用新的ES6开发,主要内容包括ReactNative的基础知识,ReactNative的布局,组件,API,封装本地API和组件,发布ReactNative App,本地与ReactNative深度结合

    57505 人正在学习 去看看 李宁

新建了一个react-native 项目

react-native init Demo
cd Demo
react-native run-android

按照顺序run的时候发现Android模拟器屏幕上显示服务器返回500的response,终端错误如标题所示:
React Native starter project bundling fails with Unexpected Token error
参考链接
https://stackoverflow.com/questions/45725376/react-native-starter-project-bundling-fails-with-unexpected-token-error
主要是babel-preset-react-native3.0.0的一些bug,先在package.json中将该行改为
"babel-preset-react-native": "2.1.0",
在终端

rm -rf node_modules
npm install

之后再run就可以啦 ^^

2019-05-21 20:00:34 dolacmeng 阅读数 286
  • 完全征服React Native

    React Native是Facebook于2015年推出的跨平台开发工具,可用于开发Android和iOS App,并且同时具有混合开发的优点(热更新,跨平台)以及本地App的性能。 本课程采用新的ES6开发,主要内容包括ReactNative的基础知识,ReactNative的布局,组件,API,封装本地API和组件,发布ReactNative App,本地与ReactNative深度结合

    57505 人正在学习 去看看 李宁

上一篇介绍了如何在已有iOS项目中集成React Native。这一篇我们把上一篇的demo做下拓展,添加点击电影跳转到详情页。页面跳转使用React Native推荐的第三方导航控件:react-navigation

集成react-navigation

  1. 根据官方指引,在终端cd到项目根目录,分别输入以下命令进行集成:

npm install --save react-native-navigation
npm install --save react-native-gesture-handler
react-native link react-native-gesture-handler

  1. 在iOS项目中,打开Podfile文件,添加RCTLinkingIOS:
pod 'React', :path => '../node_modules/react-native', :subspecs => [
    . . . // other subspecs
    'RCTLinkingIOS',
    . . .
  ]

然后执行以下命令安装

pod install
至此,react-navigation集成完毕。

使用react-navigation

  1. 参考官方使用文档,在根目录创建Navigator.js文件,编辑内容如下:
import React from "react";
import { createStackNavigator, createAppContainer } from 'react-navigation'
import HotMovie from './src/page/HotMovie';
import MovieDetail from './src/page/MovieDetail'

const AppNavigator = createStackNavigator(
  {
    Home: HotMovie,
    Details: MovieDetail
  },
  {
    initialRouteName: "Home"
  }
)

const AppContainer = createAppContainer(AppNavigator);
export default class Navigator extends React.Component {
  render() {
    return <AppContainer />;
  }
}

其中HotMovie为上一篇中创建的电影列表,MovieDetail为新建的电影详情页,具体如下一步

  1. 创建MovieDetail.js文件,路径为./src/page/MovieDetail.js,编辑如下:
import React,{Component} from 'react';
import {StyleSheet,Image,Text,View} from 'react-native';

export default class MovieDetail extends Component<Props>{
	constructor(props){
		super(props)
		const { navigation } = props
    	const itemId = navigation.getParam('itemId', 'NO-ID')
    	const cover = navigation.getParam('cover')

    	this.state = {
    	  detail:null,
    	  cover:cover,
    	  itemId:itemId
    	}

    	this.fetchData = this.fetchData.bind(this)
	}
	
	componentDidMount(){
		const requrest_url = "https://movie.douban.com/j/subject_abstract?subject_id="+this.state.itemId
    	this.fetchData(requrest_url)
  	}

	fetchData(requrest_url){
    fetch(requrest_url)
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          detail:responseJson.subject
        });
      })
 	}

	render(){
		
		if (!this.state.detail) {
			return this.renderLoadingView();
		}
		const data =  this.state.detail
		const state = this.state
		return(
			<View>
			   <Text style={{fontSize:32,fontWeight:"400",padding:10}}>{data.title}</Text>
			   <View style={styles.detailView}>
			   	  <Image style={styles.thumbnail} source={{url:state.cover}}></Image>
			   	  <View style={styles.rightDetai}>
				   	  <Text>导演: {data.directors.join('/')}</Text>
			   	  	  <Text>评分:{data.rate}</Text>
			   	  	  <Text>时长:{data.duration}</Text>
			   	  	  <Text>类型:{this.state.detail.types.join('/')}</Text>
			   	  	  <Text>主演:{this.getDetaiActor()}</Text>
			   	  </View>
			   </View>
			</View>
		)
	}

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

  	getDetaiActor(){
  		return this.state.detail.actors.slice(0,5).join('/')+' 等'
  	}
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    flexDirection:'column',
    alignItems:'center',
    justifyContent: 'center',
    alignItems: 'center',
    height:300
  },

  detailView: {
    flexDirection:'row',
    justifyContent: 'flex-start',
    height:200,
    paddingLeft:20,
    paddingTop:10,
 	paddingRight:10,
  },

  thumbnail:{
    width:79.5,
    height:121.5,
  },

  rightDetai:{
  	flexDirection:'column',
    height:200,
    marginLeft:10
  }
  
});

  1. Index.js文件修改为:
import React from 'react';
import { AppRegistry } from 'react-native';
import HotMovie from './src/page/HotMovie';
import MovieDetail from './src/page/MovieDetail'
import Navigator from './Navigator';

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

  1. 在iOS项目中,跳转ViewController.m文件改为如下:
#import "ViewController.h"
#import <React/RCTRootView.h>

@interface ViewController ()

@end

@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: @"Navigator"
                         initialProperties: nil
                             launchOptions: nil];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    [self presentViewController:vc animated:YES completion:nil];
}
@end
  1. 在HotMovie.js中添加点击事件,HotMovie.js完整代码如下:
import React, { Component } from 'react';
import {StyleSheet, Image, Text, View, FlatList,TouchableOpacity} from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation'

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> {
  
  _onItemClick(item) {
    this.props.navigation.navigate('Details',{itemId:item.id,cover:item.cover,title:item.title})
  }

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

    this.renderMovie = this.renderMovie.bind(this)
    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(
      <TouchableOpacity style={styles.item} onPress={() => this._onItemClick(item)}>
        <Image source={{url:item.cover}} style={styles.thumbnail}/>
        <View style={styles.itemRight}>
          <Text>{item.title}</Text>
          <Text>{item.rate}</Text>
        </View>
      </TouchableOpacity>
    )
  }
}

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

其中this.props.navigation.navigate('Details')即为react-navigation的导航跳转方法,但此方法不能跳转相同的页面(会没有效果),如果要多次push同样的页面,需要改为:

this.props.navigation.push('Details')

导航返回的话:

this.props.navigation.goBack()
  1. 设置导航标题

根据不同的需求,我们先看下官方的示例:

  • 如果标题是固定的,定义一个名为navigationOptions的static的属性,返回一个包含配置的对象,如:
class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Home',
  };

  /* render function, etc */
}
  • 如果是需要从上层参数中获取,代码如:
class DetailsScreen extends React.Component {
  static navigationOptions = ({ navigation }) => {
    return {
      title: navigation.getParam('otherParam', 'A Nested Details Screen'),
    };
  };

  /* render function, etc */
}
  • 如果要修改标题,代码如:
<Button
    title="Update the title"
    onPress={() => this.props.navigation.setParams({otherParam: 'Updated!'})}
  />
  • 如果需要修改样式,代码如::
class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Home',
    headerStyle: {
      backgroundColor: '#f4511e',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold',
    },
  };

  /* render function, etc */
}
  • 以上只是设置了首页的导航栏样式,我们希望全局设置,那直接回到最前面createStackNavigator代码处,修改:
const RootStack = createStackNavigator(
  {
    Home: HomeScreen,
    Details: DetailsScreen,
  },
  {
    initialRouteName: 'Home',
    /* The header config from HomeScreen is now here */
    defaultNavigationOptions: {
      headerStyle: {
        backgroundColor: '#f4511e',
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    },
  }
);

  • 有时,我们想把标题改为自定义控件,例如显示图片或者按钮,我们可以这样:
class LogoTitle extends React.Component {
  render() {
    return (
      <Image
        source={require('./spiro.png')}
        style={{ width: 30, height: 30 }}
      />
    );
  }
}

class HomeScreen extends React.Component {
  static navigationOptions = {
    // headerTitle instead of title
    headerTitle: <LogoTitle />,
  };

  /* render function, etc */
}

回到我们的demo示例,我们希望整个App导航栏的背景颜色值是#f4511e,文字为白色,故在Navigator.js中统一配置,Navigator.js完整代码如下:

import React from "react";
import { createStackNavigator, createAppContainer } from 'react-navigation'
import HotMovie from './src/page/HotMovie';
import MovieDetail from './src/page/MovieDetail'

const AppNavigator = createStackNavigator(
  {
    Home: HotMovie,
    Details: MovieDetail
  },
  {
    defaultNavigationOptions: {
      headerTintColor: '#fff',
      headerStyle: {
        backgroundColor: '#f4511e',
      },
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    },
    navigationOptions: {
      tabBarLabel: 'Home!',
    },
  }
)

const AppContainer = createAppContainer(AppNavigator);
export default class Navigator extends React.Component {
  render() {
    return <AppContainer />;
  }
}

首页(电影列表)的导航栏标题为指定图片movie.png (对应路径为:项目根目录/src/images/movie.png),故修改HotMovie.js为:

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

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"

class LogoTitle extends React.Component {
  render() {
    return (
      <Image
        source={require('../image/movie.png')}
        style={{ width: 30, height: 30 }}
      />
    );
  }
}

export default class HotMovie extends Component<Props> {

  static navigationOptions = {
     headerTitle: <LogoTitle />,
  };

  //....省略代码
}

const styles = StyleSheet.create({
	//...省略代码  
});

在电影详情页,我们根据上一页面传递来的电影名称参数来设置标题,缺省值为电影详情:

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

export default class MovieDetail extends Component<Props>{

	static navigationOptions = ({ navigation }) => {
		return {
			title:navigation.getParam('title','电影详情')
		}
	}

	//...省略代码
}

const styles = StyleSheet.create({
  //...省略代码
});


完整源代码:https://github.com/dolacmeng/RNProject/tree/master
运行效果:

在这里插入图片描述

在这里插入图片描述

2016-06-26 10:02:49 whuhan2013 阅读数 3734
  • 完全征服React Native

    React Native是Facebook于2015年推出的跨平台开发工具,可用于开发Android和iOS App,并且同时具有混合开发的优点(热更新,跨平台)以及本地App的性能。 本课程采用新的ES6开发,主要内容包括ReactNative的基础知识,ReactNative的布局,组件,API,封装本地API和组件,发布ReactNative App,本地与ReactNative深度结合

    57505 人正在学习 去看看 李宁

官方给我们提供了UIExplorer项目,这里边包含React Native的基本所有组件的使用介绍和方法。

运行官方DEMO步骤如下

  • 安装react native环境
  • React Native项目源码下载
  • 下载安装cygwin软件
  • 下载安装NDK然后安装以及配置
  • 添加Node依赖模块:该命令行需要切到react-native项目中,主要运行如下命令
    cd react-native以及npm install(这里发生错误,是因为npm需要升级的缘故)
  • 还需要安装配置python2版本,python3不行
  • 开始编译官方实例UIExploerer项目
    打开之前安装的cygwin终端,切换到当前react-native项目中。注意切换路径方法以实际项目路径为准,运行以下命令
    ./gradlew :Examples:UIExplorer:android:app:installDebug
    需要下载很多东西,挺慢的,而且由于网络原因,经常会失败,多试几次才行
  • 接下来就是最关键的一步啦~执行如下命令进行打包启动服务.
    ./packager/packager.sh

References

windows版本编译运行react-native官方实例

效果如下

该DEMO包含了react native主要组件与API的实例

COMPONETS

  • ActivityIndicatorExample
  • SliderExample
  • ImageExample
  • ListViewExample等

AIPS

  • AccessibilityAndroidExample
  • AlertExample
  • AppStateExample
  • BorderExample

官方Movie实例

The Movies app is a demonstration of basic concepts, such as fetching data, rendering a list of data including images, and navigating between different screens.

Running this app

Before running the app, make sure you ran:

git clone https://github.com/facebook/react-native.git
cd react-native
npm install

Running on Android

You’ll need to have all the prerequisites (SDK, NDK) for Building React Native installed.

Start an Android emulator (Genymotion is recommended).

cd react-native
./gradlew :Examples:Movies:android:app:installDebug
./packager/packager.sh

Note: Building for the first time can take a while.

Open the Movies app in your emulator.

See Running on Device in case you want to use a physical device.

effect

这里写图片描述

React Native 笔记

阅读数 196

没有更多推荐了,返回首页