Reputation: 7844
I'm extending a React.Component
to render a Navigator
:
<Navigator
renderScene={this.renderScene}
navigationBar={
<NavigationBar
routeMapper={NavigationBarRouteMapper}
style={styles.navBar} **// background colour is set here**
/>
/>
and passing along the navigator object the scene being rendered:
renderScene = (route, navigator) => {
if(route.maps) {
return <MapView navigator={navigator} />;
}
return <LoginScreen navigator={navigator} />;
}
and MapView
looks something like this:
type Props = {
navigator: Navigator;
}
class BTMapView extends React.Component {
props: Props;
constructor(props: Props) {
super(props);
...
}
}
So now that I can reference the navigator object with this.props.navigator
how do I use it to override the background colour of its navigation bar with an imperative API call?
SOLUTION:
class BTNavigator extends React.Component {
constructor(props) {
super(props);
this.state = {
navBarStyle: styles.navBar,
};
}
render() {
return (
<Navigator
style={styles.container}
initialRoute={{}}
renderScene={this.renderScene}
navigationBar={
<NavigationBar
routeMapper={NavigationBarRouteMapper}
style={this.state.navBarStyle}
/>
}
/>
);
}
renderScene = (route, navigator) => {
...
// pass both navigator and a reference to this
return <LoginScreen navigator={navigator} btNavigator={this} />
}
setNavBarStyle(style) {
this.setState({
navBarStyle: style,
});
}
}
Now use navigator
and btNavigator
:
type Props = {
navigator: Navigator,
btNavigator: BTNavigator,
};
class LoginScreen extends React.Component {
props: Props;
foo() {
this.props.btNavigator.setNavBarStyle({
backgroundColor: 'black',
});
this.props.navigator.push({
...
})
}
}
Upvotes: 0
Views: 1019
Reputation: 4485
First make NavigatorWrapper
class that will store Navigator
and some additional state and method eg.
setNavBarRed() {
this.setState({navBarColor: 'red'});
}
In render()
method render Navigator
just like you have written above with additional check for NavigationBar
style. Just set backgroundColor: this.state.navBarColor
in styles.
And finally, now you can use your prop: this.props.navigatorWrapper.setNavBarRed()
Please note that if you are using connect
from react-redux
you need to pass withRef
argument to connect
call.
Upvotes: 1