React Native 在Android中的实际使用(一)
React Native 在Android中的实际使用
本文作者实现的效果
从头开始开发从效果中可以看出,这是某App的首页效果,看了是不是觉得与Android原生还是可以媲美一下呢?下面,我们就来实现这个效果。 第一步:新建项目 import {
AppRegistry
} from 'react-native';
//这里采取分包方案,方便后期维护
import MainPageTest from "./appTest2";
AppRegistry.registerComponent('MainPageTest',() => MainPageTest);
上面的appTest2是作者新建的一个JS文件,用来加强代码的结构性,这里的index.android.js只做入口,不做功能和业务。 import React,{Component} from 'react';
import {
Text,View,ActivityIndicator,ListView,Image,TouchableOpacity
} from 'react-native';
这些代码读者需要特别注意,但凡是下面代码中用到的控件都需要用上述方式import,否则,会报undefind错误。 export default class extends Component {
constructor(props) {
super(props);
}
}
在appTest2.js中,我们需要首先写上这段代码,作为class入口和class构造函数。 render() {
return (
<View style={styles.container}>
<Text>开始开发</Text>
</View>
);
这段代码用来渲染界面。其中的styles作者抽出来放在了外部。如下: import styles from './style/index.css';
需要在项目目录下新建一个style文件夹,在style文件夹下新建一个index.css.js文件。代码贴出来: import {
StyleSheet,Dimensions,PixelRatio,} from 'react-native';
var deviceWidth = Dimensions.get('window').width;
var pix = Dimensions.get('window').pixelDepth;
//所有的style配置于此
export default StyleSheet.create({
container: {
paddingTop: 16,paddingBottom: 16,flex: 1,flexDirection: 'column',backgroundColor: '#F5FCFF',},);
今天我们只画出Banner。Banner是一个ViewPager,这里我们使用github上的一个开源控件[react-native-viewpager] 在使用前,需要进入您的项目目录执行npm install react-native-viewpager –save,执行成功之后才能使用。 import ViewPager from 'react-native-viewpager';
this.state = ({
viewPagerDataSource: (new ViewPager.DataSource({pageHasChanged: (r1,r2) => r1 !== r2})).cloneWithPages(data),});
return (
<ViewPager
style={this.props.style}
dataSource={this.state.viewPagerDataSource}
renderPage={this._renderPage.bind(this)}
isLoop={true}
autoPlay={false}/>
);
//渲染Banner图片 _renderPage(data) { return ( <Image source={{uri: data.imgUrl}} style={styles.page}/> ); }
上述步骤非常重要,viewpager必须先设置数据源,在没有请求网络的情况下,在构造函数中初始化数据源即可。这里只写实现方法,并不会一行行解释代码,请读者自行实现,如果遇到问题,请联系作者。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |