React Native_综合练习(获取网络数据&0.43版本后的Navigator插件)

首先把需要用到的资源文件,放到Xcode项目中

资源链接:https://pan.baidu.com/s/1hafWP4qbang9BCj0N_2yJw 密码:6rra

TabBar和NavigationBar应用到iOS项目中,drawable-xxhdpi应用到安卓项目中。

新建项目目录文件

这里写图片描述

App.js文件

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

import WTMain from './Component/WTMain'

export default class App extends Component {
  render() {
    return (
        <WTMain />
    );
  }
}

自定义tabBar

WTTabBar.js文件

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

import PropTypes from 'prop-types';

export default class WTTabBar extends Component {
    static propTypes={
        goToPage:PropTypes.func, //跳转到Tab的方法
        activeTab:PropTypes.number,//选中的下标
        tabs:PropTypes.array,//tabs的集合!像OC items的数组

        //接下来,拓展自定义的属性
        tabIconNames:PropTypes.array,//Item图片的名称
        tabNames:PropTypes.array,//保存图片的名称
        tabIconSelectedName:PropTypes.array,//保存选中图片的集合
    }
    render() {
        return (
            <View style={styles.tabsStyle}>
                {/*返回一个一个的Item*/}
                {this.props.tabs.map((tab,i)=>this.renderItem(tab,i))}//遍历集合,返回对象和角标。调用回调方法,传递值tab,i
            </View>
        );
    }
    renderItem(tab,i){
        //判断i是否是当前选中的tab!
        const color = this.props.activeTab == i ? "orange":"black";
        const currentImages = this.props.activeTab == i ? this.props.tabIconSelectedName:this.props.tabIconNames;
        return(
            <TouchableOpacity
                activeOpacity={1}//取消高亮
                onPress={()=>this.props.goToPage(i)}
                key={i}
                style={styles.tab}
            >
                <View style={styles.tabItem}>
                    <Image //图标
                        source={{uri:currentImages[i]}}
                        style={{width:30,height:30}}
                    >

                    </Image>
                    {/*文字*/}
                    <Text style={{color:color}}>{this.props.tabNames[i]}</Text>
                </View>

            </TouchableOpacity>
        )
    }
}

const styles = StyleSheet.create({
    tabsStyle:{
        flexDirection:'row',
        height:50
    },
    tabItem:{
        justifyContent:'center',
        alignItems:'center'
    },
    tab:{
        flex:1
    }
});

WTMain.js文件

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

//引入三方框架
import ScrollableTabView, { DefaultTabBar, ScrollableTabBar} from 'react-native-scrollable-tab-view';

//引入其他的模块
import WTHome from './WTHome';
import WTFind from './WTFind';
import WTMessage from './WTMessage';
import WTMine from './WTMine';

//引入自定义TabBar
import WTTabBar from './WTTabBar'

export default class WTMain extends Component {

    constructor(props){
        super(props);
        this.state={
           tabNames:['首页','我的','发现','消息'],
           tabIconNames:['tabbar_home','tabbar_profile','tabbar_discover','tabbar_message_center'],
           tabIconSelectedName:['tabbar_home_highlighted','tabbar_profile_highlighted','tabbar_discover_highlighted','tabbar_message_center_highlighted']
        }
    }

    render() {
        let tabNames = this.state.tabNames;
        let tabIconNames=this.state.tabIconNames;
        let tabIconSelectedName=this.state.tabIconSelectedName;

        return (
            <ScrollableTabView renderTabBar={()=><WTTabBar
                tabNames={tabNames}
                tabIconNames={tabIconNames}
                tabIconSelectedName = {tabIconSelectedName}
            />}
              tabBarPosition='bottom'
              //切换效果
              scrollWithoutAnimation={true}
               //常用属性
               onChangeTab={
                   (obj)=>{
                       console.log('切换到了'+obj.i);
                   }
               }
               onScroll={
                   //Float
                   (posit)=>{
                       console.log('监听到滚动'+posit);
                   }
               }
                //锁住滚动
                locked={true}
            >
             <WTHome tabLabel="首页"/>
             <WTMine tabLabel="我的"/>
             <WTFind tabLabel="发现"/>
             <WTMessage tabLabel="消息"/>
            </ScrollableTabView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});

这里写图片描述

适配安卓

将资源文件drawable-xxhdpi复制到安卓项目中的res文件夹下

这里写图片描述

使用AndroidStudio运行项目,注意图片的命名

这里写图片描述

我们发现Android设备也是可以正常运行的

这里写图片描述

获取网络数据

WTHome.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

import WTCellView from './WTCellView';

export default class WTHome extends Component {
    //

    constructor(props){
        super(props);
        this.state={
            //cell的数据
            dataSource:new ListView.DataSource({
                rowHasChanged:(r1,r2) => r1!==r2
            }),
            base_url:'http://api.budejie.com/api/api_open.php?a=list&c=data&type=29'
        }
    }

    render() {
        return (
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderRow}
                style={{backgroundColor:'#dddddd',paddingTop:10}}
            >

            </ListView>
        );
    }

    renderRow(rowData){
        return(
            <TouchableOpacity activeOpacity={0.5}

            >
                <View style={styles.cellStyle}>
                    {/*上部分*/}
                    <View style={styles.topViewStyle}>
                        {/*图片*/}
                        <Image source={{uri:rowData.profile_image}} style={{width:40,height: 40,borderRadius:20}}/>
                        {/*名字*/}
                        <Text style={styles.nameStyle}>{rowData.name}</Text>
                    </View>
                    {/*正文*/}
                    <Text style={styles.textStyle}>{rowData.text}</Text>
                </View>
            </TouchableOpacity>
        )
    }

    componentDidMount() {
        //发送网络请求
        this.loadData();
    }

    //网络请求发送
    loadData(){
        fetch(this.state.base_url)
            .then((response)=>response.json())
            .then((responseJson)=>{
                //拿到数据
                var jsonData = responseJson.list;
                //更新数据
                this.setState({
                    dataSource:this.state.dataSource.cloneWithRows(jsonData)
                })
            })
    }
}

const styles = StyleSheet.create({
    cellStyle:{
        marginTop:10,
        marginLeft:5,
        marginRight:5,
        borderBottomWidth:0.5,
        borderBottomColor:'#dddddd',
        backgroundColor:'white',
        padding:5
    },
    topViewStyle:{
        flexDirection:'row'
    },
    nameStyle:{
        lineHeight:40,
        textAlign:'center',
        paddingLeft:15,

    },
    textStyle:{
        padding:5
    }
});

注意!从RN 0.43版本开始,官方将停止维护Navigator,建议大家迁移到新的react-navigation库(文档地址需翻墙)。新的导航库无论从性能还是易用性上都要大大好于老的Navigator!
react-navigation库

在你的 React Native 项目中安装react-navigation这个包

cd 到你的项目目录
npm install –save react-navigation

这里写图片描述

WTMain.js

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


//引入三方框架
import ScrollableTabView, { DefaultTabBar, ScrollableTabBar} from 'react-native-scrollable-tab-view';
import {Navigator} from 'react-native-deprecated-custom-components';

//引入其他的模块
import WTHome from './WTHome';
import WTFind from './WTFind';
import WTMessage from './WTMessage';
import WTMine from './WTMine';

//引入自定义TabBar
import WTTabBar from './WTTabBar'



export default class WTMain extends Component {

    constructor(props){
        super(props);
        this.state={
           tabNames:['首页','我的','发现','消息'],
           tabIconNames:['tabbar_home','tabbar_profile','tabbar_discover','tabbar_message_center'],
           tabIconSelectedName:['tabbar_home_highlighted','tabbar_profile_highlighted','tabbar_discover_highlighted','tabbar_message_center_highlighted']
        }
    }
    render() {
        let tabNames = this.state.tabNames;
        let tabIconNames=this.state.tabIconNames;
        let tabIconSelectedName=this.state.tabIconSelectedName;

        return (
            <ScrollableTabView renderTabBar={()=><WTTabBar
                tabNames={tabNames}
                tabIconNames={tabIconNames}
                tabIconSelectedName = {tabIconSelectedName}
            />}
              tabBarPosition='bottom'
              //切换效果
              scrollWithoutAnimation={true}
               //常用属性
               onChangeTab={
                   (obj)=>{
                       console.log('切换到了'+obj.i);
                   }
               }
               onScroll={
                   //Float
                   (posit)=>{
                       console.log('监听到滚动'+posit);
                   }
               }
                //锁住滚动
                locked={true}
            >

                <Navigator
                    tabLabel="首页"
                    initialRoute={{
                        component:WTHome,
                        params:{
                            title:'首页'
                        }
                    }}
                    renderScene={(route,navigator)=>
                        <route.component navitator={navigator} {...route.params} />
                    }
                />

                <Navigator
                    tabLabel="我的"
                    initialRoute={{
                        component:WTMine,
                        params:{
                            title:'我的'
                        }
                    }}
                    renderScene={(route,navigator)=>
                        <route.component navitator={navigator} {...route.params} />
                    }
                />
                <Navigator
                    tabLabel="发现"
                    initialRoute={{
                        component:WTFind,
                        params:{
                            title:'发现'
                        }
                    }}
                    renderScene={(route,navigator)=>
                        <route.component navitator={navigator} {...route.params} />
                    }
                />
                <Navigator
                    tabLabel="消息"
                    initialRoute={{
                        component:WTMessage,
                        params:{
                            title:'消息'
                        }
                    }}
                    renderScene={(route,navigator)=>
                        <route.component navitator={navigator} {...route.params} />
                    }
                />

            </ScrollableTabView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});

WTHome.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

import WTCellView from './WTCellView';

export default class WTHome extends Component {

    constructor(props){
        super(props);
        this.state={
            //cell的数据
            dataSource:new ListView.DataSource({
                rowHasChanged:(r1,r2) => r1!==r2
            }),
            base_url:'http://api.budejie.com/api/api_open.php?a=list&c=data&type=29'
        }
    }

    render() {
        return (
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderRow.bind(this)}
                style={{backgroundColor:'#dddddd',paddingTop:10}}
            >

            </ListView>
        );
    }

    renderRow(rowData){
        var that = this;
        return(

                <View style={styles.cellStyle}>
                    <TouchableOpacity activeOpacity={0.5}
                                      onPress={that.pushTo}
                    >
                    {/*上部分*/}
                    <View style={styles.topViewStyle}>
                        {/*图片*/}
                        <Image source={{uri:rowData.profile_image}} style={{width:40,height: 40,borderRadius:20}}/>
                        {/*名字*/}
                        <Text style={styles.nameStyle}>{rowData.name}</Text>
                    </View>
                    {/*正文*/}
                    <Text style={styles.textStyle}>{rowData.text}</Text>
                    </TouchableOpacity>
                </View>

        )
    }
    pushTo(){

        this.props.navitator.push(
            {
                component:WTCellView,
                params:{
                    title:'cell'
                }
            }
        )

    }


    componentDidMount() {
        //发送网络请求
        this.loadData();
    }

    //网络请求发送
    loadData(){
        fetch(this.state.base_url)
            .then((response)=>response.json())
            .then((responseJson)=>{
                //拿到数据
                var jsonData = responseJson.list;
                //更新数据
                this.setState({
                    dataSource:this.state.dataSource.cloneWithRows(jsonData)
                })
            })
    }
}

const styles = StyleSheet.create({
    cellStyle:{
        marginTop:10,
        marginLeft:5,
        marginRight:5,
        borderBottomWidth:0.5,
        borderBottomColor:'#dddddd',
        backgroundColor:'white',
        padding:5
    },
    topViewStyle:{
        flexDirection:'row'
    },
    nameStyle:{
        lineHeight:40,
        textAlign:'center',
        paddingLeft:15,

    },
    textStyle:{
        padding:5
    }
});

因为Navigator已经被废弃,所以本文中的Navigator会出现报错的情况,解决方案有待研究。下篇文章我们研究下官方推荐的react-navigation

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值