為React Native項目配置Navigator(路由)

此文章只適合新手,老司機如有寶貴意見請多提。

App

/**
 * Created by function on 2017/3/9.
 */
import React, {Component} from 'react';
//導(dǎo)入對應(yīng)的頁面文件
import Home from './Home'
import {
    StyleSheet,
    View,
    Text,
    Navigator
} from 'react-native';

export default class App extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        let defaultName = 'Home';
        let defaultComponent = Home;
        return (
            /**
             * initialRoute:指定了默認的頁面,也就是啟動app之后會看到界面的第一屏。 需要填寫兩個參數(shù): name 跟 component。
             * configureScene:頁面之間跳轉(zhuǎn)時候的動畫和手勢,具體請看官方文檔
             * renderScene:導(dǎo)航欄可以根據(jù)指定的路由來渲染場景,調(diào)用的參數(shù)是路由和導(dǎo)航器
             */
            <Navigator
                initialRoute={{name: defaultName, component: defaultComponent}}
                configureScene={(route) => {
                    return Navigator.SceneConfigs.VerticalDownSwipeJump;
                }}
                renderScene={(route, navigator) => {
                    let Component = route.component;
                    return <Component {...route.params} navigator={navigator}/>
                }}/>
        );
    }
}

注釋意見寫得很清楚了,就不啰嗦了。

Home

/**
 * Created by function on 2017/3/11.
 */
import React, {Component} from 'react';
import SecondPage from './SecondPage';
import TextButton from '../components/TextButton';
import {
    View,
} from 'react-native';
export default class Home extends Component {

    constructor(props) {
        super(props);
    }

    _onPress = () => {
        /**
         * 為什么這里可以取得 props.navigator?請看上面的App.js:
         * <Component {...route.params} navigator={navigator} />
         * 這里傳遞了navigator作為props
         */
        const { navigator } = this.props;

        if(navigator) {
            navigator.push({
                name: 'SecondPage',
                component: SecondPage,
            })
        }
    };

    render() {
        const {counter} = this.props;
        return (
            <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
                <Text>我是第一個界面</Text>
                <TextButton onPress={this._onPress} text={'點擊跳轉(zhuǎn)'}/>
            </View>
        );
    }
}

簡單說一下,這里的頁面就是簡單的一個TextButton,點擊事件里面onPress 先獲取父頁面?zhèn)鬟^來的navigator,判斷到如果存在,那邊就push跳轉(zhuǎn)一個對面的頁面,我這里寫的是SecondPage。
哦,對,還有一個小細節(jié),細心的同志估計看到我的onPress不用這樣寫

_onPress={ this._onPress.bind (this) }

或者這樣寫

    // 構(gòu)造
    constructor(props) {
        super(props);
        // 初始狀態(tài)
        this.state = {};
        this._onPress = this._onPress.bind(this);
    }```
把方法直接作為一個arrow function的屬性來定義,初始化的時候就綁定好了this指針
寫了以后是這樣的

_onPress = () => {
const {navigator} = this.props;
if (navigator) {
navigator.push({
name: 'SecondPage',
component: SecondPage,
})
}
};

沒寫是這樣

_onPress(){
const {navigator} = this.props;
if (navigator) {
navigator.push({
name: 'SecondPage',
component: SecondPage,
})
}
};

大家對比一下就知道細節(jié)在哪里
簡單封裝一個TextButton

/**

  • Created by function on 2017/3/9.
    */
    import React, {Component} from 'react';
    import {StyleSheet, View, Text, TouchableOpacity} from 'react-native';

/**

  • 簡單封裝一個Button

  • text:顯示的內(nèi)容

  • onPress:回調(diào)
    */
    export default class TextButton extends Component {

    constructor(props) {
    super(props);
    }

    render() {
    const {text, onPress} = this.props;

     return (
         <View>
             <TouchableOpacity onPress={onPress} style={styles.button}>
                 <Text>{text}</Text>
             </TouchableOpacity>
         </View>
     );
    

    }
    }

const styles = StyleSheet.create({
button: {
width: 100,
height: 30,
padding: 10,
backgroundColor: 'lightgray',
alignItems: 'center',
justifyContent: 'center',
margin: 3
}
});

理解不了的請看注釋

##SecondPage

/**

  • Created by function on 2017/3/11.
    */
    import React, {Component} from 'react';
    import TextButton from '../components/TextButton';
    import {
    View,
    Text,
    } from 'react-native';
    export default class SecondPage extends Component {

    _onPress = () => {
    const { navigator } = this.props;
    if(navigator) {
    /**
    * 感覺就像入棧出棧
    */
    navigator.pop();
    }
    };

    render() {
    return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
    <Text style={{color: 'red'}}>我是第二個界面</Text>
    <TextButton onPress={this._onPress} text={'點擊跳回去'}/>
    </View>
    );
    }
    }

就簡單的顯示幾個文字和跳轉(zhuǎn)回去的按鈕
##來看看效果
![效果圖.gif](http://upload-images.jianshu.io/upload_images/4416446-3f0efc1b3f450666.gif?imageMogr2/auto-orient/strip)
手勢和跳轉(zhuǎn)動畫在上面說了。
如有不完善地方,歡迎討論

##帶參跳轉(zhuǎn)
按照上面的例子,加以改造。
直接上代碼吧,注釋意見寫得聽清楚的了

/**

  • Created by function on 2017/3/11.
    */
    import React, {Component} from 'react';
    import SecondPage from './SecondPage';
    import TextButton from '../components/TextButton';
    import {
    View,
    Text,
    } from 'react-native';
    export default class Home extends Component {

    // 構(gòu)造
    constructor(props) {
    super(props);
    // 初始狀態(tài)
    this.state = {
    id: 2,
    user: '',
    };
    }

    _onPress = () => {
    /**
    * 為什么這里可以取得 props.navigator?請看上面的App.js:
    * <Component {...route.params} navigator={navigator} />
    * 這里傳遞了navigator作為props
    */
    const {navigator} = this.props;

     if (navigator) {
         navigator.push({
             name: 'SecondPage',
             component: SecondPage,
             params: {
                 id: this.state.id,
                 /**
                  * 把getUser這個方法傳遞給下一個頁面獲取user
                  * @param user
                  */
                 getUser: (user) => {
                     this.setState({
                         user: user
                     })
                 }
             }
         })
     }
    

    };

    render() {
    const {user} = this.state;
    return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
    {user === '' && <Text>我是第一個界面</Text>}
    {user !== '' && <Text>用戶信息: { JSON.stringify(user) }</Text>}
    <TextButton onPress={this._onPress} text={'點擊跳轉(zhuǎn)'}/>
    </View>
    );
    }
    }

/**

  • Created by function on 2017/3/11.
    */
    import React, {Component} from 'react';
    import TextButton from '../components/TextButton';
    import {
    View,
    Text,
    } from 'react-native';

const USER = {
1: {name: 'Action', age: 23},
2: {name: 'Function', age: 25}
};

export default class SecondPage extends Component {

// 構(gòu)造
constructor(props) {
    super(props);
    // 初始狀態(tài)
    this.state = {
        id: '',
    };
}

componentDidMount() {
    /**
     *  這里獲取從上個頁面跳轉(zhuǎn)傳遞過來的參數(shù): id,賦值給this.state.id
     */
    this.setState({
        id: this.props.id
    })
}

_onPress = () => {
    const {navigator} = this.props;
    if (this.props.getUser) {
        let user = USER[this.props.id];
        this.props.getUser(user);
    }
    if (navigator) {
        /**
         * 感覺就像入棧出棧
         */
        navigator.pop();
    }
};

render() {
    return (
        <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
            <Text style={{fontSize: 15}}>獲得的參數(shù): id={ this.state.id }</Text>
            <Text style={{color: 'red'}}>我是第二個界面</Text>
            <TextButton onPress={this._onPress} text={'點擊跳回去'}/>
        </View>
    );
}

}

##效果圖


![效果圖.gif](http://upload-images.jianshu.io/upload_images/4416446-2c1b7115e00c2078.gif?imageMogr2/auto-orient/strip)
github會隨著更新而更新[https://github.com/LinsanityZ/EnjoyGossip](https://github.com/LinsanityZ/EnjoyGossip)
如有不完善地方,歡迎討論
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容