React Native組件之ScrollView 和 StatusBar和TabBarIos

來源:互聯網
上載者:User

標籤:

React Native中的組件ScrollView類似於iOS中的UIScrollView,其基本的使用方法和熟悉如下:

/** * Sample React Native App * https://github.com/facebook/react-native * 周少停 ScrollView 的常用屬性 * 2016-09-19 */import React, { Component } from ‘react‘;import {  AppRegistry,  StyleSheet,  Text,  ScrollView,  AlertIOS,  View} from ‘react-native‘;var Dimensions = require(‘Dimensions‘);var {width,height} = Dimensions.get(‘window‘);class Project extends Component {  render() {    return (      <View style={styles.container}>        <ScrollView           horizontal={true}  //排列方向:橫向  預設false縱向          showsHorizontalScrollIndicator={false}  //隱藏水平線          pagingEnabled={true}  //分頁滑動 iOS//           scrollEnabled={false}  //是否滾動 iOS          bounces={false}  //關閉彈簧效果 iOS          onScrollBeginDrag={()=>this.beginDrag()} //開始滑動時調用          onScrollEndDrag={()=>this.endDrag()} //結束滑動時調用          onMomentumScrollEnd={()=>this.momentumScroll()}//當一幀滑動完畢後調用          >            {this.renderChildView()}        </ScrollView>      </View>    );  }  renderChildView(){    //數組    var allChild = [];    var colors = [‘red‘,‘blue‘,‘yellow‘,‘cyan‘,‘purple‘];    //遍曆    for(var i=0; i<5;i++){      allChild.push(  //裝載        <View key={i} style={{backgroundColor:colors[i],width:width,height:120}}>          <Text>{i}</Text>        </View>      );    }    //返回    return allChild;  }  beginDrag(){//     AlertIOS.alert(‘開始滑動‘);  }  endDrag(){//     AlertIOS.alert(‘滑動結束‘);  }  momentumScroll(){//     AlertIOS.alert(‘一幀結束‘)  }}const styles = StyleSheet.create({  });AppRegistry.registerComponent(‘Project‘, () => Project);

  demo:

/** * Sample React Native App * https://github.com/facebook/react-native * 周少停 ScrollView demo * 2016-09-20 *///首先匯入計時器類庫://終端:  cd 項目根目錄//      npm i react-timer-mixin --save//noinspection JSUnresolvedVariableimport React, { Component } from ‘react‘;import {  AppRegistry,  StyleSheet,  Text,  ScrollView,  Image,  View} from ‘react-native‘;//引入計時器類庫var TimerMixin = require(‘react-timer-mixin‘);//引入json資料var ImageData = require(‘./imageTitleJson.json‘);//引入Dimensionsvar Dimensions = require(‘Dimensions‘);var width = Dimensions.get(‘window‘).width;var Project = React.createClass({    mixins: [TimerMixin], //註冊計時器    //設定固定值    getDefaultProps(){      return{          //時間間隔          duration : 2000      }    },    //設定page的初始值和可變值    //預設第一頁選中    getInitialState(){        return {        //當前頁碼        currentPage : 0     };    },    render() {        return (            <View style={styles.container}>                <ScrollView ref="scrollView" style={styles.scrollViewStyle}                            horizontal={true} //水平排列                            pagingEnabled={true}  //分頁滑動                            onMomentumScrollEnd={(e)=>this.onAnimationEnd(e)} //一幀結束回調,去除()表示把該組件作為參數傳過去                            onScrollBeginDrag={this.BeginDrag} //開始拖拽就停止定時器                            onScrollEndDrag={this.EndDrag} //停止拖拽就啟動定時器                >                    {this.readerAllImage()}                </ScrollView>                {/*返回六點*/}                <View style={styles.pageViewStyle}>                    {this.renderPage()}                </View>            </View>        );    },    BeginDrag(){        //停止定時器        this.clearInterval(this.timer);    },    EndDrag(){        //開啟定時器        this.startTimer();    },    //實現一些複雜操作    componentDidMount(){      //開啟定時器        this.startTimer();    },    //實現定時器    startTimer(){        //得到scrollView        var scrollView = this.refs.scrollView;        var imgsArr = ImageData.data;        //添加定時器       this.timer = this.setInterval(function () {            //設定圓點            var activePage = 0;            //判斷            if((this.state.currentPage+1) >= imgsArr.length){//越界               activePage = 0;            }else{               activePage = this.state.currentPage + 1;            }            //更新狀態機器            this.setState({               currentPage:activePage            });            //讓scorllView動起來            var offsetX = activePage * width;            scrollView.scrollResponderScrollTo({x:offsetX,y:0,animation:true});        },this.props.duration);    },    //返回圖片    readerAllImage(){        //數組        var allImage = [];        //拿到圖片數組        var imgsArr = ImageData.data;        //遍曆        for(var i=0; i<imgsArr.length;i++){            //去除單獨的image            var imgItem = imgsArr[i];            //建立組件裝入數組            allImage.push(                <Image key={i} source={{uri:imgItem.img}} style={{width:width,height:120}}/>            );        }        //返回數組        return allImage;    },    //返回圓點    renderPage(){        //定義一個數組放置所有圓點        var indicatorArr = [];        //拿到圖片數組        var imgsArr = ImageData.data;        //圓點顏色style        var style;        //遍曆        for(var i = 0;i<imgsArr.length;i++){            //判斷            style = (i==this.state.currentPage) ? {color:‘red‘} : {color:‘white‘}            //裝載進數組中            indicatorArr.push(                <Text key={i} style={[{fontSize:25},style]}>•</Text>            );        }        return indicatorArr;    },    //當一幀結束時,調用    onAnimationEnd(e){        //求出水平方向的位移量        var offSetX = e.nativeEvent.contentOffset.x;        //求出當前的page        var currentPage =  Math.floor(offSetX/width);        //更新狀態機器,修改繪製UI        this.setState({           currentPage : currentPage        });     }});const styles = StyleSheet.create({  container:{   marginTop:20  },  scrollViewStyle:{  },  pageViewStyle: {    width:width,    height:25,    backgroundColor:‘rgba(0,0,0,0)‘,    position:‘absolute‘,//絕對位置    bottom:0,    bottom:0,    flexDirection:‘row‘,//主軸方向    alignItems:‘center‘  }});AppRegistry.registerComponent(‘Project‘, () => Project);

  React Native 中StatusBar的相關屬性,其他一些屬性只限於安卓,一些屬性只限於iOS,具體看React Native中文網

/** * Sample React Native App * https://github.com/facebook/react-native * 周少停 2016-09-27 * StatusBar狀態列 * **/import React, { Component } from ‘react‘;import {    AppRegistry,    StyleSheet,    Text,    View,    StatusBar,} from ‘react-native‘;class  Project extends  Component{    render() {        return (            <View style={styles.container}>                <StatusBar                   // hidden = {true}  //status顯示與隱藏                   // backgroundColor = ‘red‘  //status欄背景色,僅支援安卓                   // translucent = {true} //設定status欄是否透明效果,僅支援安卓                   //  barStyle = ‘light-content‘ //設定狀態列文字效果,僅支援iOS,枚舉類型:default黑light-content白                    networkActivityIndicatorVisible = {true} //設定狀態列上面的網路進度菊花,僅支援iOS                    showHideTransition = ‘slide‘ //顯隱時的動畫效果.預設fade                />            </View>        );    }}const styles = StyleSheet.create({    container: {        flex: 1,        justifyContent: ‘center‘,        alignItems: ‘center‘,        backgroundColor: ‘#F5FCFF‘,    }});AppRegistry.registerComponent(‘Project‘, () => Project);

React NAtive中的TabBarIos也就是iOS中的UITabBarController,這裡的TabBarIos僅可以iOS使用,若需安卓也適用,可以尋求第三方庫。

/** * Sample React Native App * https://github.com/facebook/react-native * 周少停  TabBarIos TabBarIos.Item * 2016-09-22 */import React, { Component } from ‘react‘;import {  AppRegistry,  StyleSheet,  Text,  TabBarIOS,  View} from ‘react-native‘;var Project = React.createClass({  //設定初始值  getInitialState(){    return{      //預設選中第一個Item      selectedTabBarItem: ‘home‘    }  },  render() {    return (      <View style={styles.container}>        <TabBarIOS barTintColor=‘black‘>          <TabBarIOS.Item            systemIcon="bookmarks"            badge="3"            selected = {this.state.selectedTabBarItem == ‘home‘}            onPress = {()=>{this.setState({selectedTabBarItem: ‘home‘})}}          >            <View style={[styles.commonViewStyle,{backgroundColor: ‘red‘}]}>              <Text>首頁</Text>            </View>          </TabBarIOS.Item>          <TabBarIOS.Item              systemIcon="more"              selected = {this.state.selectedTabBarItem == ‘second‘}              onPress = {()=>{this.setState({selectedTabBarItem: ‘second‘})}}          >            <View style={[styles.commonViewStyle,{backgroundColor:‘yellow‘}]}>              <Text>第二頁</Text>            </View>          </TabBarIOS.Item>          <TabBarIOS.Item              systemIcon="downloads"              selected = {this.state.selectedTabBarItem == ‘three‘}              onPress = {()=>{this.setState({selectedTabBarItem: ‘three‘})}}          >            <View style={[styles.commonViewStyle,{backgroundColor:‘cyan‘}]}>              <Text>第三頁</Text>            </View>          </TabBarIOS.Item>          <TabBarIOS.Item              // systemIcon="contacts"              icon = {require(‘./1.png‘)}              badge="6"              selected = {this.state.selectedTabBarItem == ‘four‘}              onPress = {()=>{this.setState({selectedTabBarItem: ‘four‘})}}          >            <View style={[styles.commonViewStyle,{backgroundColor:‘blue‘}]}>              <Text>第四頁</Text>            </View>          </TabBarIOS.Item>        </TabBarIOS>      </View>    );  }});const styles = StyleSheet.create({  container:{    flex:1,    backgroundColor:‘#f5fcff‘,  },  commonViewStyle:{    flex:1,    justifyContent:‘center‘,    alignItems:‘center‘  }});AppRegistry.registerComponent(‘Project‘, () => Project);

  

 

完整源碼下載:https://github.com/pheromone/React-Native-1

 

React Native組件之ScrollView 和 StatusBar和TabBarIos

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.