react-navigation使用之嵌套和跳轉


1. 新版react-native已經將react-navigation作為官方版本發布,基礎Demo可以從官方網站獲得,比較困擾的問題是組件的嵌套和第二、第三頁面的跳轉。

2. 組件嵌套問題:

要在父組件定義出指定父組件的router=子組件的router;同時,在子組件賦值navigation屬性。

class AllContactsScreen extends React.Component {
    render() {return (
            <View>
                <Text>List of all contacts</Text>
                <ItemBlock title="hello world" navigation={this.props.navigation}/>
            </View>
        );
    }
}
AllContactsScreen.router = ItemBlock.router;

在子組件中定義跳轉函數,子組件的代碼如下:

export default class ItemBlock extends Component{
    render(){return(
            <View>
                <Button
                    onPress={this.click.bind(this)}
                    title="Chat with Lily"
                />
            </View>
        );
    }
    click(){
        const { navigate } = this.props.navigation;
        navigate('Chat');     }
}

3. 第二、第三頁面的跳轉,也是在定義StackNavigator時指定,StackNavigator只定義一次。

const SimpleApp = StackNavigator({
    Home: {
        screen: MainScreenNavigator,
        navigationOptions: {
            title: 'My Chats',
        },
    },
    Chat: { screen: ChatScreen },
    ChatDetail: {screen: ChatDetail}
})

第二頁面的代碼如下:

export  default  class ChatScreen extends React.Component {
    static navigationOptions = {
        title: 'Chat with Lucifa',
    };
    render() {
        return(
            <View>
                <Button
                    onPress={this.click.bind(this)}
                    title="Chat with Lucky"
                />
            </View>
        );
    }
    click(){
        const { navigate } = this.props.navigation;
        navigate('ChatDetail');
    }
}

第三頁面就可以隨便寫了。

以上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM