Just want to add another solution, especially when Navigator is used to render the scene.
If this is the case, then the above solutions won't work as it doesn't have access to ref specified in the DrawerLayoutAndroid
, and it will in fact return
"undefined is not an object (evaluating 'this.refs['DRAWER_REF']')"
or something like that.
Solution:
Create our own Toolbar so that we can pass our rendering component to it.
MyToolbar.js
... import stuff ...
module.exports = React.createClass({
render: function() {
return (
<ToolbarAndroid
title={this.props.title}
navIcon = {{uri: "ic_menu_white_24dp", isStatic: true}}
style = {styles.toolbar}
titleColor='#FFFFFF'
onIconClicked={this._onIconClicked}/>
);
},
_onIconClicked: function(){
this.props.sidebarRef.refs['DRAWER'].openDrawer();
// sidebarRef is the rendering component we're passing
}
});
OpenDrawerFromToolbar.js
...
module.exports = React.createClass({
render: function() {
var navigationView = (
<View style={{flex: 1, backgroundColor: '#fff'}}>
<Text style={{margin: 10, fontSize: 15, textAlign: 'left'}}>In the Drawer!</Text>
</View>
);
return (
<View style={styles.container}>
<DrawerLayoutAndroid drawerWidth = {300}
drawerPosition = {DrawerLayoutAndroid.positions.Left}
renderNavigationView = {() => navigationView}
ref={'DRAWER'}>
<MyToolbar style={styles.toolbar}
title={'My Awesome App'}
navigator={this.props.navigator}
sidebarRef={this}/> // pass the component to MyToolbar
<View style = {{flex: 1, alignItems: 'center'}}>
<Text style = {{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text>
<Text style = {{margin: 10, fontSize: 15, textAlign: 'right'}}>World!</Text>
</View>
</DrawerLayoutAndroid>
</View>
);
},
_setDrawer: function() {
this.refs['DRAWER'].openDrawer();
}
});
Then our Navigator component with its renderingScene function will work:
module.exports = React.createClass({
render: function() {
return (
<Navigator
style = {styles.container}
initialRoute = {{ name: 'openDrawerFromToolbar', index: 0 }}
renderScene = {this.navigatorRenderScene}
configureScene={ () => { return Navigator.SceneConfigs.PushFromRight; }}/>
);
},
navigatorRenderScene: function(route, navigator) {
_navigator = navigator;
return (
<OpenDrawerFromToolbar
route={route}
navigator={navigator}
data={route.data}/>
);
}
});