import React from "react";
import { BackHandler } from "react-native";
import { NavigationActions } from "react-navigation";
/* your other setup code here! this is not a runnable snippet */
class ReduxNavigation extends React.Component {
componentDidMount() {
BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
}
onBackPress = () => {
const { dispatch, nav } = this.props;
if (nav.routes[0].index === 0) {
return false;
}
dispatch(NavigationActions.back());
return true;
};
render() {
/* more setup code here! this is not a runnable snippet */
return <AppNavigator navigation={navigation} />;
}
}
实例:
import React from 'react'
import {BackHandler} from 'react-native'
import {connect} from 'react-redux'
import {createBottomTabNavigator,createAppContainer,NavigationActions} from 'react-navigation'
import Ionicons from 'react-native-vector-icons/Ionicons'
import MaterialIcons from 'react-native-vector-icons/MaterialIcons'
import Popular from './Popular'
import Trending from './Trending'
import Favorites from './Favorites'
import My from './My'
class Home extends React.Component{
createBottom(){
if (this.TabBottom) {
return this.TabBottom
}
let BottomNavigator = createBottomTabNavigator(
{
Popular:{
screen:Popular,
navigationOptions: {
title:"热门",
tabBarIcon:({focused, horizontal, tintColor})=>{
return <Ionicons name={'ios-thumbs-up'} size={25} color={tintColor} />
}
}
},
Trending:{
screen: Trending,
navigationOptions: {
title: "趋势",
tabBarIcon:({focused, horizontal, tintColor})=>{
return <MaterialIcons name={'directions-run'} size={25} color={tintColor} />
}
}
},
Favorites:{
screen:Favorites,
navigationOptions:{
title:"收藏",
tabBarIcon:({focused, horizontal, tintColor})=>{
let name = focused?'md-heart':'md-heart-empty'
return <Ionicons name={name} size={25} color={tintColor} />
}
}
},
My:{
screen:My,
navigationOptions:{
title:"我的",
tabBarIcon:({focused, horizontal, tintColor})=>{
return <Ionicons name={'logo-freebsd-devil'} size={25} color={tintColor} />
}
}
}
},
{
tabBarOptions:{
activeTintColor:this.props.color
}
}
)
return this.TabBottom = createAppContainer(BottomNavigator)
// return createAppContainer(BottomNavigator)
}
componentDidMount() {
BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
}
onBackPress = () => {
const { dispatch, nav } = this.props;
console.log(this.props.nav)
// return true
alert(nav.routes[0].index)
if (nav.routes[0].index === 0) {
return false;
}
dispatch(NavigationActions.back());
return true;
};
render(){
Popular.navigation = this.props.navigation
const BottomBar = this.createBottom()
return <BottomBar/>
}
}
// 从store中取出主题颜色
const mapStateToProps = state=>({
color:state.theme.color,
nav:state.nav
})
export default connect(mapStateToProps)(Home)