React native navigationOptions calling function error - react-native

Got an error when call a function inside navigationOptions.
static navigationOptions = {
tabBarIcon: ({ tintColor })=> (
<Icon name='ios-add-circle' style={{ color: tintColor}} />
),
tabBarOnPress: () => {
this.callingFun();
},
}
callingFun = ()=> {
console.log('tabBarOnPress:');
}
Error:

You can not call callingFun in static object property. I think that you want this
static navigationOptions = ({navigation}) => {
return {
tabBarIcon: ({ tintColor }) => (
<Icon name='ios-add-circle' style={{ color: tintColor }} />
),
tabBarOnPress: () => {
navigation.getParam('callingFun')();
},
}
}
callingFun = () => {
console.log('tabBarOnPress:');
}
componentDidMount() {
const { navigation } = this.props
navigation.setParams({
callingFun: this.callingFun,
})
}

Static method calls are made on the class, not on the instance. There is no way to reference this in static method. Can only reach a static method using the name of the class.
export default class MediaTab extends React.Component {
static navigationOptions = {
tabBarIcon: ({ tintColor })=> (
<Icon name='ios-add-circle' style={{ color: tintColor}} />
),
tabBarOnPress: () => {
MediaTab.callingFun();
},
}
static callingFun = () => {
console.log('tabBarOnPress:');
}
}

I've resolved the issue be the following way:
static navigationOptions = ({ navigation }) => {
return {
headerRight: () => (
<TouchableOpacity
onPress={navigation.getParam('onPressSyncButton')}>
<Text>Sync</Text>
</TouchableOpacity>
),
};
};
componentDidMount() {
this.props.navigation.setParams({ onPressSyncButton: this._onPressSyncButton });
}
_onPressSyncButton = () => {
console.log("function called");
}

const BottomTab = createMaterialTopTabNavigator({
Active:OnlineStack
}, {
tabBarPosition: 'top',
tabBarOptions: {
activeTintColor: 'gray',
inactiveTintColor: 'white',
labelStyle: {
fontSize: 12,
fontFamily: "Choco_Cooky"
},
style: {
backgroundColor: 'black',
borderWidth: 1,
borderBottomWidth:0,
borderColor: 'gray',
},
}
/* Other configuration remains unchanged */
}
);
OnlineStack.navigationOptions = ({navigation})=>{
let { routeName } = navigation.state.routes[navigation.state.index];
let navigationOptions = {};
header: null;
if (routeName === 'Home') {
navigationOptions.tabBarVisible = false;
}
return navigationOptions;
}

Related

Drawer does not open on first touch

I have a header that should open a drawer once it is touched. However the current behaviour is that it shows immediately the Profile screen (the drawer does not open) on first touch. If you touch the header again then the drawer is actually shown.
import ...
const navigationOptions = (navigation) => {
return {
title: navigation.screenProps.t('app.title')
}
}
const defaultNavigationOptionsWithHeader = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: Colors.backgroundColor,
},
headerTintColor: Colors.main,
headerTitleStyle: {
fontWeight: 'bold'
},
headerRight: <TouchableOpacity style={{ marginRight: 10 }} onPress={() => navigation.dispatch(DrawerActions.openDrawer())}>
<Ionicons
name={Platform.OS === 'ios'
? 'ios-menu'
: 'md-menu'}
size={40}
color={Colors.main}
/>
</TouchableOpacity>
}
}
const defaultNavigationOptionsWithoutHeader = ({ navigation }) => {
return {
headerStyle: {
backgroundColor: Colors.backgroundColor,
},
headerTintColor: Colors.main,
headerTitleStyle: {
fontWeight: 'bold'
}
}
}
const AuthStack = createStackNavigator(
{
Login: {
screen: LoginScreen,
navigationOptions: navigationOptions
},
Registration: {
screen: RegistrationScreen,
navigationOptions: navigationOptions
}
}, {
initialRouteName: 'Login',
defaultNavigationOptions: defaultNavigationOptionsWithoutHeader
});
const TabStack = createStackNavigator(
{
App: {
screen: TabNavigator,
navigationOptions: navigationOptions
}
}, {
defaultNavigationOptions: defaultNavigationOptionsWithHeader
}
);
const MenuStack = createStackNavigator(
{
App: {
screen: MenuNavigator,
navigationOptions: navigationOptions
}
}, {
defaultNavigationOptions: defaultNavigationOptionsWithHeader
}
);
const appNavigationOptions = (navigation) => {
return {
initialRouteName: 'Tab'
}
}
const AppStack = createSwitchNavigator(
{
Tab: TabStack,
Menu: MenuStack
},
{
defaultNavigationOptions: appNavigationOptions
}
)
export default createAppContainer(createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
Auth: AuthStack,
App: AppStack
},
{
initialRouteName: 'AuthLoading',
}
));
Does anybody know what causes this issue? The menu navigator is defined as follows:
import ...
handleHome = (navigation) => {
navigation.navigate('App')
}
handleLogout = (navigation) => {
logout();
navigation.navigate('Auth')
}
const config = Platform.select({
web: { headerMode: 'screen' },
default: {},
});
const navigationOptions = (navigation) => {
return {
header: null
}
}
const ProfileStack = createStackNavigator(
{
Map: {
screen: ProfileScreen,
navigationOptions: navigationOptions
}
},
config
);
ProfileStack.navigationOptions = (navigation) => {
return {
drawerLabel: navigation.screenProps.t('loggedin.sidebar.profile'),
drawerIcon: ({ focused }) => (<DrawerIcon
focused={focused}
name={
Platform.OS === 'ios'
? `ios-contact'}`
: 'md-contact'
}
/>)
};
}
ProfileStack.path = '';
const PreferencesStack = createStackNavigator(
{
Settings: {
screen: PreferencesScreen,
navigationOptions: navigationOptions
}
},
config
);
PreferencesStack.navigationOptions = (navigation) => {
return {
drawerLabel: navigation.screenProps.t('loggedin.sidebar.preferences'),
drawerIcon: ({ focused }) => (<DrawerIcon
focused={focused}
name={
Platform.OS === 'ios'
? `ios-settings'}`
: 'md-settings'
}
/>)
}
};
const LogoutStack = createStackNavigator(
{
Logout: {
screen: () => null,
navigationOptions: navigationOptions
}
},
config
);
LogoutStack.navigationOptions = (navigation) => {
return {
drawerLabel: navigation.screenProps.t('button.logout'),
drawerIcon: ({ focused }) => createDrawerIcon('log-out', focused)
};
}
const TabStack = createStackNavigator(
{
Logout: {
screen: () => null,
navigationOptions: navigationOptions
}
},
config
);
TabStack.navigationOptions = (navigation) => {
return {
drawerLabel: navigation.screenProps.t('app.title'),
drawerIcon: ({ focused }) => createDrawerIcon('home', focused)
};
}
createDrawerIcon = (icon, focused = false) => {
return <DrawerIcon
focused={focused}
name={
Platform.OS === 'ios'
? 'ios-' + icon
: 'md-' + icon
}
/>
}
const MenuDrawerItem = (props) => {
return <TouchableOpacity onPress={props.onPress} >
<View style={styles.item}>
<View style={styles.iconContainer}>
{createDrawerIcon(props.icon)}
</View>
<Text style={styles.label}>{props.text}</Text>
</View>
</TouchableOpacity >
}
const MenuDrawer = (props) => (
<ScrollView contentContainerStyle={{ flex: 1, flexDirection: 'column', justifyContent: 'space-between' }}>
<SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
<MenuDrawerItem onPress={() => this.handleHome(props.navigation)} text={props.screenProps.t('app.title')} icon={'home'} />
<DrawerItems {...props} />
</SafeAreaView>
<MenuDrawerItem onPress={() => this.handleLogout(props.navigation)} text={props.screenProps.t('button.logout')} icon={'log-out'} />
</ScrollView>
);
const menuNavigator = createDrawerNavigator({
ProfileStack,
PreferencesStack
}, {
drawerPosition: 'right',
contentComponent: props => <MenuDrawer {...props} />,
contentOptions: {
activeTintColor: Colors.main
},
initialRouteName: 'ProfileStack'
}
);
menuNavigator.path = ''
export default menuNavigator
const styles = ...
That's probably you might have something other in focus.
May be Keyboard, TextField, Or some other things which are in focus and when you click for the first time the focus gets removed and when you press for the second time the drawer gets opened.
Try calling an alert instead of opening the drawer on button press and then debug that. That will troubleshoot the issue

Header is not visible in react native

import React, {Component} from 'react';
import {Text, View,TextInput,Button,Alert,KeyboardAvoidingView,ScrollView,Dimensions,TouchableOpacity} from 'react-native';
import AsyncStorage from '#react-native-community/async-storage';
import {BoxShadow} from 'react-native-shadow'
import DropdownAlert from 'react-native-dropdownalert';
import datum from './data';
import Parse from "parse/react-native";
export default class Editprofile extends React.Component {
static navigationOptions = {
title: 'Edit Profile',
headerStyle: {
backgroundColor:'#E8EDF1',
},
headerTintColor:datum.primaryColor,
headerTitleStyle: {
fontWeight: 'bold',
textAlign:"center",
flex:1
},
};
constructor(props) {
super(props)
this.state = {name:"",number:0,windowwidth:Dimensions.get('window').width,windowheight:Dimensions.get('window').height,custid:""};
}
componentDidMount() {
Parse.setAsyncStorage(AsyncStorage);
getData = async () => {
try {
const value = await AsyncStorage.getItem('nameKey')
if(value !== null) {
this.setState({name:await AsyncStorage.getItem('nameKey')
,number: await AsyncStorage.getItem('numberKey')})
const GameScore = Parse.Object.extend("Customer");
const query = new Parse.Query(GameScore);
query.equalTo("phonenumber",parseInt(this.state.number));
const results = await query.find();
for (let i = 0; i < results.length; i++) {
var object = results[i];
this.setState({custid:JSON.stringify(object.id)})
}
}
} catch(e) {
this.dropdown.alertWithType('error', 'Error', 'Error reading values');
}
}
getData();
}
updatedata = async () => {
try {
await AsyncStorage.setItem('nameKey',this.state.name)
await AsyncStorage.setItem('numberKey',this.state.number)
var P = Parse.Object.extend("Customer");
var instance = new P();
var temp=this.state.custid.replace(/['"]+/g, '')
var temptwo=temp.replace(/\//g, "")
instance.id = temptwo.replace(/['"]+/g, '')
instance.set("name",this.state.name);
instance.set("phonenumber",parseInt(this.state.number));
instance.save();
this.dropdown.alertWithType('success', 'Success', 'saved locally ');
} catch (e) {
this.dropdown.alertWithType('error', 'Error', 'Cannot able to create profile');
}
}
render() {
const shadowOpt = {
width:this.state.windowwidth*0.5,
height:this.state.windowheight*0.07,
color:"#000",
border:26,
radius:3,
opacity:0.2,
x:0,
y:3,
style:{marginVertical:5}
}
return (
<View style={{flex:1,flexDirection:'column',justifyContent:'space-evenly',alignItems:'center',backgroundColor:'#E8EDF1'}}>
<BoxShadow setting={shadowOpt}>
<TextInput
placeholderTextColor={datum.placeholderTextColor}
style={{
height: this.state.windowheight*0.07, borderColor:datum.primaryColor, borderWidth: 1,
width:this.state.windowwidth*0.5,backgroundColor:datum.primaryColor, fontWeight: '200',elevation: 2
}}
onChangeText={(value) => this.setState({name:value.trim()})}
value={this.state.name}
/>
</BoxShadow>
<BoxShadow setting={shadowOpt}>
<TextInput
placeholderTextColor={datum.placeholderTextColor}
keyboardType='number-pad'
style={{height: this.state.windowheight*0.07, borderColor:datum.primaryColor, borderWidth: 1,width:this.state.windowwidth*0.5,backgroundColor:datum.primaryColor, fontWeight: '200'}}
onChangeText={(value) => this.setState({number:value})}
value={this.state.number}
/>
</BoxShadow>
<BoxShadow setting={shadowOpt}>
<Button
onPress={()=>this.updatedata()
}
title="Signup"
color={datum.primaryColor}
accessibilityLabel="Learn more about this purple button"
/>
</BoxShadow>
<DropdownAlert ref={ref => this.dropdown = ref} />
</View>
);
}
}
I am using drawer navigation in this project but I don't understand why the header is not visible in my project it is blank, can someone say how to add a header to my component so that I can run out of complaints, I am struggling with this error for past two weeks
react-natvigation is used in the project ,
my app.js
const MyDrawerNavigator = createDrawerNavigator({
entry:{
screen:SIgnup,
navigationOptions: {
drawerLabel: () => null
},
},
Home: {
screen: HOme,
navigationOptions: {
drawerLabel: 'Home',
drawerIcon: ({ tintColor }) => (
<Image
source={require("./components/Drawbles/Homeicon.png")}
resizeMode="contain"
style={{ width: 20, height: 20 }}
/>
)
}
},
Editprofile: {
screen: EDit,
navigationOptions: {
drawerLabel: 'Edit Profile',
drawerIcon: ({ tintColor }) => (
<Image
source={require("./components/Drawbles/EditProfile.png")}
resizeMode="contain"
style={{ width: 20, height: 20, tintColor: tintColor }}
/>
)
}
},
Offerrides: {
screen: OFferrides,
navigationOptions: {
drawerLabel: 'Offer Rides',
drawerIcon: ({ tintColor }) => (
<Image
source={require("./components//Drawbles/Offerride.png")}
resizeMode="contain"
style={{ width: 20, height: 20 }}
/>
)
}
},
Paymentmethod: {
screen: PAymentmethod,
navigationOptions: {
drawerLabel: 'Home',
drawerIcon: ({ tintColor }) => (
<Image
source={require("./components/Drawbles/Paymentmethod.png")}
resizeMode="contain"
style={{ width: 20, height: 20 }}
/>
)
}
},
Otp: {
screen: OTp,
navigationOptions: {
drawerLabel: () => null //hide header if not needed so whole screen slide
},
}
},{});
const MyApp = createAppContainer(MyDrawerNavigator);
export default MyApp;
Drawer navigation by default doesn't display the header,it just display the drawing menu. As it is you can open the drawer by sliding right,if you want to open it with a header you have to do a component and use it on screens you want. Heres a nice example of headers: https://react-native-training.github.io/react-native-elements/docs/header.html
Try change this:
static navigationOptions = {
...props...
}
To this:
static navigationOptions = () => {
return {
...props...
}
}

How to send value with react-navigation in static filed?

I have a screen set a <Switch /> in header by using react navigation.
I know how to get this.state value from outside function by this.props.navigation.setParams.
But I don't know how to send the <Switch /> value to outside function.
I try it with the code onValueChange={value => params.handleThis(value)}
but in my case handleThis is key-value, it can't get the value obviously.
this.props.navigation.setParams({
handleThis: this.changeSwitch
});
How to send <Switch /> onChange value to outside function ?
Here is my code:
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
title: 'Title',
headerStyle: {
backgroundColor: ColorSetting.headerColor,
elevation: null,
},
headerTitleStyle: {
fontWeight: '300',
fontFamily: 'FFF Tusj',
fontSize: 18
},
headerRight:
<View style={{ marginRight: 15 }}>
<Switch
onValueChange={value => params.handleThis()}
value={params.switchOn}
onTintColor='#444444'
tintColor='#444444'
/>
</View>,
};
};
constructor(props) {
super(props);
this.state = {
switchOn: false
};
}
componentDidMount() {
this.props.navigation.setParams({
handleThis: this.changeSwitch
});
}
changeSwitch = () => {
const { switchOn, titleVersion } = this.state;
this.props.navigation.setParams({ switchOn: !switchOn });
this.setState({ switchOn: !switchOn });
}
Any help would be appreciated. Thanks in advance.
You can use params.handleThis as the handler, there is no need for an inline function.
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
title: 'SO Question',
headerStyle: {
elevation: null,
},
headerTitleStyle: {
fontFamily: 'FFF Tusj',
fontSize: 18
},
headerRight:
<View style={{ marginRight: 15 }}>
<Switch
onValueChange={params.handleThis}
value={params.switchOn}
onTintColor='#444444'
tintColor='#444444'
/>
</View>,
};
};
after that changeSwitch will receive the new value as the first parameter.
changeSwitch = (switchOn) => {
this.props.navigation.setParams({ switchOn });
this.setState({ switchOn });
}
Here's a working example

How to put this.props data into headerRight selector?

I use react-redux to get my FlatList data and custom my header with react-navigation.
I want to add a selector in headerRight, my problem is I have no idea how to add the data into my headerRight.
Here is my header setting.
const data = [
{ key: 0, section: true, label: 'Title' },
{ key: 1, label: 'Red Apples' },
{ key: 2, label: 'Cherries' },
{ key: 3, label: 'Cranberries', accessibilityLabel: 'Tap here for cranberries' },
{ key: 4, label: 'Vegetable', customKey: 'Not a fruit' }
];
class MovieTimeList extends Component {
static navigationOptions = ({ navigation }) => ({
title: `${navigation.state.params.theaterCn}`,
headerStyle: {
backgroundColor: '#81A3A7',
elevation: null,
},
headerTitleStyle: {
fontWeight: '300',
fontFamily: 'FFF Tusj',
fontSize: 18
},
headerRight:
<ModalSelector
data={data}
initValue="Title"
onChange={(option)=>{ alert(`${option.label} (${option.key}) nom nom nom`) }}
/>,
});
Here is my react-redux mapStateToProps function that action is call an API to get the data:
const mapStateToProps = (state) => {
const timeList = state.listType.timeList;
return { timeList };
};
I can show the movieData in FlatList from react-redux:
render() {
const movieData = this.props.timeList;
return (
<View style={{ flex: 1 }}>
<FlatList
data={movieData}
renderItem={this.renderRow}
horizontal={false}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
I have no idea how to let the const movieData into my headerRight selector.
Any help would be appreciated. Thanks in advance.
You can set param and then use it in your header like this
componentWillReceiveProps(nextProp){
if(!isFetching && listNotUpdated){
this.props.navigation.setParams({ movieList: nextProp.timeList})
}
}
then get it in the header like this
static navigationOptions = ({ navigation }) => {
const { state } = navigation
const { movieList }= navigation.state.params
return {
title: 'Your Title',
headerRight: (
<Button
title={'Button1'}
onPress={() => {
// do something
}}
/>
),
}
}
I am not sure if this code is 100% correct, basically, you can do it by connecting ur reducer to your MovieTimeList class pass necessary prop to your component
class MovieTimeList extends Component {
static navigationOptions = ({ navigation }) => ({
title: `${navigation.state.params.theaterCn}`,
headerStyle: {
backgroundColor: '#81A3A7',
elevation: null,
},
headerTitleStyle: {
fontWeight: '300',
fontFamily: 'FFF Tusj',
fontSize: 18
},
headerRight:
<ModalSelector
data={data}
initValue={this.props.HeaderTitle}
onChange={(option)=>{ alert(`${option.label} (${option.key}) nom nom nom`) }}
/>,
});
const mapStateToProps = (state) => {
let HeaderTitle = state.yourreducer.headerTitle
return HeaderTitle
}
export default connect(mapStateToProps,null)(MovieTimeList)

React Native component life cycle - which function gets called when screen is visible

I've been looking at the documentation here https://reactjs.org/docs/react-component.html, but there is something that keeps bugging me. A pattern which I almost constantly seem to need but I am unable to find a solution to it and so always have to find hacks around it.
The pattern that I'm talking about is as follows. My app has a TabNavigator and I understand that when the app gets initialised ComponentDidMount is called on all the tabs. What I would like are functions that get called when a Tab is either navigated to, using this.props.navigation.navigate('TAB1') or when the tab is clicked at the bottom of the screen.
If someone can help with this I'd really appreciate it. Apologies there is no code to show for this.
Thanks
First, to understand the reason why it's not so easy, read the following conversation in the corresponding issue: https://github.com/react-navigation/react-navigation/issues/51
Here is what currently looks like the most effective solution: https://github.com/react-navigation/react-navigation/pull/3345
And this is the example code you can try out:
import type {
NavigationScreenProp,
NavigationEventSubscription,
} from 'react-navigation';
import React from 'react';
import { Button, Platform, ScrollView, StatusBar, View } from 'react-native';
import { SafeAreaView, TabNavigator } from 'react-navigation';
import Ionicons from 'react-native-vector-icons/Ionicons';
import SampleText from './SampleText';
const MyNavScreen = ({ navigation, banner }) => (
<SafeAreaView forceInset={{ horizontal: 'always', top: 'always' }}>
<SampleText>{banner}</SampleText>
<Button
onPress={() => navigation.navigate('Home')}
title="Go to home tab"
/>
<Button
onPress={() => navigation.navigate('Settings')}
title="Go to settings tab"
/>
<Button onPress={() => navigation.goBack(null)} title="Go back" />
<StatusBar barStyle="default" />
</SafeAreaView>
);
const MyHomeScreen = ({ navigation }) => (
<MyNavScreen banner="Home Tab" navigation={navigation} />
);
MyHomeScreen.navigationOptions = {
tabBarTestIDProps: {
testID: 'TEST_ID_HOME',
accessibilityLabel: 'TEST_ID_HOME_ACLBL',
},
tabBarLabel: 'Home',
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-home' : 'ios-home-outline'}
size={26}
style={{ color: tintColor }}
/>
),
};
type MyPeopleScreenProps = {
navigation: NavigationScreenProp<*>,
};
class MyPeopleScreen extends React.Component<MyPeopleScreenProps> {
_s0: NavigationEventSubscription;
_s1: NavigationEventSubscription;
_s2: NavigationEventSubscription;
_s3: NavigationEventSubscription;
static navigationOptions = {
tabBarLabel: 'People',
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-people' : 'ios-people-outline'}
size={26}
style={{ color: tintColor }}
/>
),
};
componentDidMount() {
this._s0 = this.props.navigation.addListener('willFocus', this._onEvent);
this._s1 = this.props.navigation.addListener('didFocus', this._onEvent);
this._s2 = this.props.navigation.addListener('willBlur', this._onEvent);
this._s3 = this.props.navigation.addListener('didBlur', this._onEvent);
}
componentWillUnmount() {
this._s0.remove();
this._s1.remove();
this._s2.remove();
this._s3.remove();
}
_onEvent = a => {
console.log('EVENT ON PEOPLE TAB', a.type, a);
};
render() {
const { navigation } = this.props;
return <MyNavScreen banner="People Tab" navigation={navigation} />;
}
}
type MyChatScreenProps = {
navigation: NavigationScreenProp<*>,
};
class MyChatScreen extends React.Component<MyChatScreenProps> {
_s0: NavigationEventSubscription;
_s1: NavigationEventSubscription;
_s2: NavigationEventSubscription;
_s3: NavigationEventSubscription;
static navigationOptions = {
tabBarLabel: 'Chat',
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-chatboxes' : 'ios-chatboxes-outline'}
size={26}
style={{ color: tintColor }}
/>
),
};
componentDidMount() {
this._s0 = this.props.navigation.addListener('willFocus', this._onEvent);
this._s1 = this.props.navigation.addListener('didFocus', this._onEvent);
this._s2 = this.props.navigation.addListener('willBlur', this._onEvent);
this._s3 = this.props.navigation.addListener('didBlur', this._onEvent);
}
componentWillUnmount() {
this._s0.remove();
this._s1.remove();
this._s2.remove();
this._s3.remove();
}
_onEvent = a => {
console.log('EVENT ON CHAT TAB', a.type, a);
};
render() {
const { navigation } = this.props;
return <MyNavScreen banner="Chat Tab" navigation={navigation} />;
}
}
const MySettingsScreen = ({ navigation }) => (
<MyNavScreen banner="Settings Tab" navigation={navigation} />
);
MySettingsScreen.navigationOptions = {
tabBarLabel: 'Settings',
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-settings' : 'ios-settings-outline'}
size={26}
style={{ color: tintColor }}
/>
),
};
const SimpleTabs = TabNavigator(
{
Home: {
screen: MyHomeScreen,
path: '',
},
People: {
screen: MyPeopleScreen,
path: 'cart',
},
Chat: {
screen: MyChatScreen,
path: 'chat',
},
Settings: {
screen: MySettingsScreen,
path: 'settings',
},
},
{
lazy: true,
removeClippedSubviews: true,
tabBarOptions: {
activeTintColor: Platform.OS === 'ios' ? '#e91e63' : '#fff',
},
}
);
type SimpleTabsContainerProps = {
navigation: NavigationScreenProp<*>,
};
class SimpleTabsContainer extends React.Component<SimpleTabsContainerProps> {
static router = SimpleTabs.router;
_s0: NavigationEventSubscription;
_s1: NavigationEventSubscription;
_s2: NavigationEventSubscription;
_s3: NavigationEventSubscription;
componentDidMount() {
this._s0 = this.props.navigation.addListener('willFocus', this._onAction);
this._s1 = this.props.navigation.addListener('didFocus', this._onAction);
this._s2 = this.props.navigation.addListener('willBlur', this._onAction);
this._s3 = this.props.navigation.addListener('didBlur', this._onAction);
}
componentWillUnmount() {
this._s0.remove();
this._s1.remove();
this._s2.remove();
this._s3.remove();
}
_onAction = a => {
console.log('TABS EVENT', a.type, a);
};
render() {
return <SimpleTabs navigation={this.props.navigation} />;
}
}
export default SimpleTabsContainer;
For the source and other codes, look here: https://github.com/react-navigation/react-navigation/blob/master/examples/NavigationPlayground/js/SimpleTabs.js