一个简单的ReactNative demo

本人非前端,请轻喷 ReactNative版本:0.31 github:https://github.com/X-FAN/reactnativelearn

代码做了一些简单的注释,下面是源码

import React, {
    Component
}
    from 'react';
import {
    AppRegistry,
    Navigator,
    ToastAndroid
}
    from 'react-native';

import LoginComponet from './LoginComponet'

class AwesomeProject extends Component {
    render() {
        let defaultName = 'LoginComponet';
        let defaultComponent = LoginComponet;
        return (
            <Navigator
                initialRoute={{name: defaultName, component: defaultComponent}}
                configureScene={(route) => {//定义跳转的方式,禁用手势拖动跳转
                    return {...Navigator.SceneConfigs.FadeAndroid, gestures: false};
                }}
                renderScene={(route, navigator) => {
                    let Component = route.component;
                    //路由的参数和navigator都传入到跳转的component内
                    return <Component {...route} navigator={navigator}/>
                }}/>
            //{...route} 将route的每个属性都传过去
        );
    }
}
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
import React, {
    Component,
    PropTypes
} from 'react';
import {
    View,
    TextInput,
    StyleSheet,
    TouchableNativeFeedback,
    Text,
    TouchableHighlight,
    Navigator
} from 'react-native'

import AndroidGankComponent from './AndroidGankComponent'

class LoginComponet extends Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
        };
    }

    check(username, password) {
        if (username.length == 0) {
            ToastAndroid.show('请填写账号', ToastAndroid.LONG)
        } else if (password.length == 0) {
            ToastAndroid.show('请填写密码', ToastAndroid.LONG);
        } else {
            this.props.navigator.push({//跳转到AndroidGankComponent
                name: 'AndroidGankComponent',
                component: AndroidGankComponent,
            })
        }
    }

    render() {
        return (
            <View style={{margin: 10, flex: 1, flexDirection: 'column'}}>
                <TextInput style={[styles.basic, {marginTop: 30}] }
                           placeholderTextColor='#757575'
                           placeholder='请输入账号'
                           onChangeText={(text)=> {
                               this.setState({username: text});
                           }}/>
                <TextInput style={styles.basic}
                           placeholderTextColor='#757575'
                           placeholder='请输入密码'
                           onChangeText={(text)=> {
                               this.setState({password: text});
                           }}/>
                <TouchableNativeFeedback
                    background={TouchableNativeFeedback.SelectableBackground()}
                    onPress={()=>this.check(this.state.username, this.state.password)}
                >
                    <View style={{borderRadius: 10, backgroundColor: '#0097A7', marginTop: 30}}>
                        <Text style={styles.text}>登录</Text>
                    </View>
                </TouchableNativeFeedback>
            </View>
        );
    }
}

/**
 * 样式封装
 */
const styles = StyleSheet.create({
    basic: {
        padding: 10
    },
    text: {
        fontSize: 18,
        color: '#FFFFFF',
        margin: 10,
        textAlign: 'center'
    }
});

export default  LoginComponet;
import  React, {
    Component
} from 'react'
import {
    View,
    Text,
    ListView,
    ToastAndroid,
    StyleSheet,
    BackAndroid,
    Image,
    TouchableHighlight,
    TouchableWithoutFeedback,
    ActivityIndicator,
    RefreshControl
} from  'react-native';
import WebViewComponet from './WebViewComponet';


var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
class AndroidGankComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isRefreshing: false,
            dataSource: ds,
        };
    }

    componentWillMount() {
        this.genRows();
        BackAndroid.addEventListener('hardwareBackPress', ()=>this.goBack());//监听安卓回退按钮
    }


    render() {
        if (this.state.dataSource.getRowCount() === 0) {//没有数据时展示'加载视图'
            return (
                <View style={ {flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
                    <ActivityIndicator
                        size='large'
                        color='#8BC34A'/>
                </View>
            );
        } else {
            return (
                //标题栏
                <View style={{flexDirection: 'column', flex: 1}}>
                    <View style={{flexDirection: 'row', backgroundColor: '#00BCD4', padding: 10}}>
                        <TouchableWithoutFeedback onPress={()=>this.goBack()}>
                            <Image style={{width: 30, height: 30}} source={require('./image/back.png') }/>
                        </TouchableWithoutFeedback>
                        <Text style={{fontSize: 20, color: "#FFFFFF"}}>安卓干货</Text>
                    </View>
                    <ListView
                        dataSource={this.state.dataSource}
                        renderRow={(rowData)=>this.getRow(rowData)}
                        refreshControl={//下拉刷新的配置
                            <RefreshControl
                                refreshing={this.state.isRefreshing}
                                onRefresh={()=>this.onRefresh}//刷新触发的函数
                                colors={['#8BC34A']}
                                progressBackgroundColor="#ffffff"
                            />
                        }>
                    </ListView>
                </View>
            );
        }

    }

    /**
     * 获取listview的数据源
     */
    genRows() {
        this.getAndroidGank();
    }

    /**
     * 渲染listview的每行的内容
     * @param rowData
     * @returns {XML}
     */
    getRow(rowData) {
        return (
            <TouchableWithoutFeedback onPress={()=>this.jumpToGank(rowData.url)}>
                <View style={styles.container}>
                    <Text style={styles.text}>{'标题:' + rowData.desc}</Text>
                    <Text style={styles.subText}>{'推荐人:' + rowData.who}</Text>
                </View>
            </TouchableWithoutFeedback>
        )
    }

    /**
     * 展示具体干货内容
     * @param url
     */
    jumpToGank(url) {
        this.props.navigator.push({
            url: url,
            name: 'WebViewComponet',
            component: WebViewComponet
        });
    }

    /**
     * 网络请求获取安卓干货
     */
    getAndroidGank() {
        fetch('http://gank.io/api/data/Android/10/1')
            .then((response)=> {
                return response.json();
            })
            .then((responseJson)=> {
                if (responseJson.results) {
                    this.setState({isRefreshing: false, dataSource: ds.cloneWithRows(responseJson.results)});//修改状态值,再次渲染
                }
            }).catch((error)=>console.error(error))
            .done();
    }

    /**
     * 回退
     */
    goBack() {
        const nav = this.props.navigator;
        const routers = nav.getCurrentRoutes();
        if (routers.length > 1) {
            nav.pop();
            return true;
        }
        return false;
    }

    /**
     * 下拉刷新
     */
    onRefresh() {
        this.genRows();
    }

}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'column',
        justifyContent: 'center',
        padding: 10,
        margin: 10,
        backgroundColor: '#B2EBF2',
        borderRadius: 5
    },
    text: {
        fontSize: 18,
        color: '#212121'
    },
    subText: {
        fontSize: 18,
        color: '#757575'
    }
});
export  default AndroidGankComponent;
import React, {
    Component,
} from 'react';
import {
    View,
    WebView,
    ToastAndroid,
    TouchableWithoutFeedback,
    Image,
    Text
} from 'react-native';


class WebViewComponet extends Component {

    render() {
        return (
            <View style={{flexDirection: 'column', flex: 1}}>
                <View style={{flexDirection: 'row', backgroundColor: '#00BCD4', padding: 10}}>
                    <TouchableWithoutFeedback onPress={()=>this.goBack()}>
                        <Image style={{width: 30, height: 30}} source={require('./image/back.png') }/>
                    </TouchableWithoutFeedback>
                    <Text style={{fontSize: 20, color: "#FFFFFF"}}>安卓干货</Text>
                </View>
                <WebView
                    startInLoadingState={true}
                    javaScriptEnabled={true}
                    domStorageEnabled={true}
                    source={{uri: this.props.url}}/>//根据属性里传过来的url加载
            </View>
        );
    };

    /**
     * 回退
     */
    goBack() {
        const nav = this.props.navigator;
        const routers = nav.getCurrentRoutes();
        if (routers.length > 1) {
            nav.pop();
            return true;
        }
        return false;
    }
}
export  default  WebViewComponet;

2016.9.8:引入第三方开源库react-native-scrollable-tab-view

参考: http://es6.ruanyifeng.com http://www.ruanyifeng.com/blog/2015/03/react.html https://facebook.github.io/react-native

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏逆向技术

win32程序之子窗口编程

  在前边我们已经讲解了窗口的本质.以及如何注册窗口类跟创建窗口. 还讲了消息循环.

2402
来自专栏Guangdong Qi

小Q项目框架搭建及会动的Tabbar未完待续,持续更新中

1804
来自专栏技术总结

MJRefresh源码剖析与学习

建议查看原文:https://www.jianshu.com/p/23c876f8ae39(不定时更新)

2454
来自专栏非著名程序员

基础篇章:关于 React Native 之 Navigator 组件的讲解

(友情提示:RN学习,从最基础的开始,大家不要嫌弃太基础,会的同学请自行略过,希望不要耽误已经会的同学的宝贵时间) 今天我们来讲讲Navigator这个小家伙,...

1947
来自专栏Scott_Mr 个人专栏

自定义转场详解(一)

1522
来自专栏岑志军的专栏

ReactNative-综合案例(02)

1797
来自专栏哈雷彗星撞地球

RunLoop总结:RunLoop的应用场景(五)阻止App崩溃一次

今天要介绍的RunLoop应用场景感觉很酷炫,我们可能不常用到,但是对于做Crash 收集的 SDK可能会用得比较频繁吧。相比关于RunLoop 可以让应用起死...

1232
来自专栏滕先生的博客

react native 自定义下拉刷新——桥接MJRefresh

4458
来自专栏進无尽的文章

实践-小细节Ⅵ

有时候,UITableView 的cell个数很少,可是UITableView的headView又是一个有颜色背景的View,当我们下拉的时候,拉扯出来的区域也...

762
来自专栏Charlie's Road

Container ViewController自定义转场控制器。

最近接触到新公司的老项目改版。自从来了之后一直在忙另一个项目,也没有看老项目的实现逻辑。 看到设计稿的时候,并不是普通的树形标签导航的样子。大致效果如FaceU...

1271

扫码关注云+社区

领取腾讯云代金券