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');
    }
}

第三页面就可以随便写了。

以上。