一個(gè)簡(jiǎn)單的ReactNative demo

本人非前端,請(qǐng)輕噴
ReactNative版本:0.31
github:https://github.com/X-FAN/reactnativelearn

代碼做了一些簡(jiǎn)單的注釋,下面是源碼

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) => {//定義跳轉(zhuǎn)的方式,禁用手勢(shì)拖動(dòng)跳轉(zhuǎn)
                    return {...Navigator.SceneConfigs.FadeAndroid, gestures: false};
                }}
                renderScene={(route, navigator) => {
                    let Component = route.component;
                    //路由的參數(shù)和navigator都傳入到跳轉(zhuǎn)的component內(nèi)
                    return <Component {...route} navigator={navigator}/>
                }}/>
            //{...route} 將route的每個(gè)屬性都傳過去
        );
    }
}
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('請(qǐng)?zhí)顚戀~號(hào)', ToastAndroid.LONG)
        } else if (password.length == 0) {
            ToastAndroid.show('請(qǐng)?zhí)顚懨艽a', ToastAndroid.LONG);
        } else {
            this.props.navigator.push({//跳轉(zhuǎn)到AndroidGankComponent
                name: 'AndroidGankComponent',
                component: AndroidGankComponent,
            })
        }
    }

    render() {
        return (
            <View style={{margin: 10, flex: 1, flexDirection: 'column'}}>
                <TextInput style={[styles.basic, {marginTop: 30}] }
                           placeholderTextColor='#757575'
                           placeholder='請(qǐng)輸入賬號(hào)'
                           onChangeText={(text)=> {
                               this.setState({username: text});
                           }}/>
                <TextInput style={styles.basic}
                           placeholderTextColor='#757575'
                           placeholder='請(qǐng)輸入密碼'
                           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());//監(jiān)聽安卓回退按鈕
    }


    render() {
        if (this.state.dataSource.getRowCount() === 0) {//沒有數(shù)據(jù)時(shí)展示'加載視圖'
            return (
                <View style={ {flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
                    <ActivityIndicator
                        size='large'
                        color='#8BC34A'/>
                </View>
            );
        } else {
            return (
                //標(biāo)題欄
                <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}//刷新觸發(fā)的函數(shù)
                                colors={['#8BC34A']}
                                progressBackgroundColor="#ffffff"
                            />
                        }>
                    </ListView>
                </View>
            );
        }

    }

    /**
     * 獲取listview的數(shù)據(jù)源
     */
    genRows() {
        this.getAndroidGank();
    }

    /**
     * 渲染listview的每行的內(nèi)容
     * @param rowData
     * @returns {XML}
     */
    getRow(rowData) {
        return (
            <TouchableWithoutFeedback onPress={()=>this.jumpToGank(rowData.url)}>
                <View style={styles.container}>
                    <Text style={styles.text}>{'標(biāo)題:' + rowData.desc}</Text>
                    <Text style={styles.subText}>{'推薦人:' + rowData.who}</Text>
                </View>
            </TouchableWithoutFeedback>
        )
    }

    /**
     * 展示具體干貨內(nèi)容
     * @param url
     */
    jumpToGank(url) {
        this.props.navigator.push({
            url: url,
            name: 'WebViewComponet',
            component: WebViewComponet
        });
    }

    /**
     * 網(wǎng)絡(luò)請(qǐng)求獲取安卓干貨
     */
    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)});//修改狀態(tài)值,再次渲染
                }
            }).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}}/>//根據(jù)屬性里傳過來的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

**2016.11.18 **更新界面設(shè)計(jì)

效果圖

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市芭商,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,729評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件佳励,死亡現(xiàn)場(chǎng)離奇詭異季研,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)狮惜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門高诺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人碾篡,你說我怎么就攤上這事虱而。” “怎么了开泽?”我有些...
    開封第一講書人閱讀 169,461評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵牡拇,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我穆律,道長(zhǎng)惠呼,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,135評(píng)論 1 300
  • 正文 為了忘掉前任峦耘,我火速辦了婚禮剔蹋,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘辅髓。我一直安慰自己泣崩,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,130評(píng)論 6 398
  • 文/花漫 我一把揭開白布洛口。 她就那樣靜靜地躺著律想,像睡著了一般。 火紅的嫁衣襯著肌膚如雪绍弟。 梳的紋絲不亂的頭發(fā)上技即,一...
    開封第一講書人閱讀 52,736評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音樟遣,去河邊找鬼而叼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛豹悬,可吹牛的內(nèi)容都是我干的葵陵。 我是一名探鬼主播,決...
    沈念sama閱讀 41,179評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼瞻佛,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼脱篙!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起伤柄,我...
    開封第一講書人閱讀 40,124評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤绊困,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后适刀,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體秤朗,經(jīng)...
    沈念sama閱讀 46,657評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,723評(píng)論 3 342
  • 正文 我和宋清朗相戀三年笔喉,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了取视。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片硝皂。...
    茶點(diǎn)故事閱讀 40,872評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖作谭,靈堂內(nèi)的尸體忽然破棺而出稽物,到底是詐尸還是另有隱情,我是刑警寧澤折欠,帶...
    沈念sama閱讀 36,533評(píng)論 5 351
  • 正文 年R本政府宣布贝或,位于F島的核電站,受9級(jí)特大地震影響怨酝,放射性物質(zhì)發(fā)生泄漏傀缩。R本人自食惡果不足惜那先,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,213評(píng)論 3 336
  • 文/蒙蒙 一农猬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧售淡,春花似錦斤葱、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至汤纸,卻和暖如春衩茸,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背贮泞。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工楞慈, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人啃擦。 一個(gè)月前我還...
    沈念sama閱讀 49,304評(píng)論 3 379
  • 正文 我出身青樓囊蓝,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親令蛉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子聚霜,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,876評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容