Reputation: 107
I have the code below, and what I wish to achieve is to change the state of Tabscreen
from one of the screens in TabNavigator
. But way in which I am currently trying to do this, with a global function to set the state, simply does not work, with the error undefined is not a function (evaluating 'this.setstate')
import React from 'react';
import {Image, Text, TouchableNativeFeedback, TouchableHighlight} from 'react-native';
import {TabNavigator} from 'react-navigation';
import {Container, Header, Icon, Left, Body} from 'native-base';
import Timeline from './Timeline';
const Mainscreen=TabNavigator(
{
Main:{
screen: Timeline,
navigationOptions:{
tabBarIcon: ({tintColor}) => <Icon name='home' style={{color:tintColor}}/>
}
},
Search:{
screen: props => <Container><TouchableHighlight onPress={()=>globalStateUpdate()}><Container style={{backgroundColor:'rgba(0,132,180,0.5)'}}></Container></TouchableHighlight></Container>,
navigationOptions:{
tabBarIcon: ({tintColor}) => <Icon name='search' style={{color:tintColor}}/>
}
},
}
);
function globalStateUpdate(){
this.setState({
header:<Text>Search</Text>
});
}
class Tabscreen extends React.Component {
constructor(props){
super(props);
this.state={
header:<Text>Home</Text>
};
globalStateUpdate = globalStateUpdate.bind(this);
}
render() {
return (
<Container>
<Header hasTabs >
<Left>
{this.state.header}
</Left>
<Body/>
</Header>
<Mainscreen/>
</Container>
);
}
}
export default Tabscreen;
How can I do this? React-navigation is extremely important to my application and I cannot remove that. I believe Redux is something that solves this but it seems overly complicated for just a single change of text, which is all I need.
Upvotes: 2
Views: 2572
Reputation: 5135
You can pass the function from your TabScreen
to other screens to update TabScreen
state.
const Mainscreen=TabNavigator(
{
Main:{
screen: Timeline,
navigationOptions:{
tabBarIcon: ({tintColor}) => <Icon name='home' style={{color:tintColor}}/>
}
},
Search:{
screen: props => <Container><TouchableHighlight onPress={()=> props.screenProps.globalStateUpdate({header:<Text>Search</Text>})}><Container style={{backgroundColor:'rgba(0,132,180,0.5)'}}></Container></TouchableHighlight></Container>,
navigationOptions:{
tabBarIcon: ({tintColor}) => <Icon name='search' style={{color:tintColor}}/>
}
},
}
);
class Tabscreen extends React.Component {
constructor(props){
super(props);
this.state={
header:<Text>Home</Text>
globalStateUpdate: newState => this.setState(newState)
};
}
render() {
return (
<Container>
<Header hasTabs >
<Left>
{this.state.header}
</Left>
<Body/>
</Header>
<Mainscreen screenProps={{globalStateUpdate: this.state.globalStateUpdate}} />
</Container>
);
}
}
Upvotes: 1