我想再提供另一种解决方案,特别是当使用 Navigator 渲染场景时。
如果是这种情况,上面的解决方案将无法工作,因为它无法访问 DrawerLayoutAndroid
中指定的 ref,实际上会返回
"undefined is not an object (evaluating 'this.refs['DRAWER_REF']')"
或类似的东西。
解决方案:
创建我们自己的工具栏,以便我们可以将我们的渲染组件传递给它。
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();
}
});
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();
}
});
然后我们的导航器组件及其渲染场景函数将起作用:
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}/>
);
}
});
this.refs['DRAWER_REF']
只能从渲染抽屉的组件中访问。如果您想从视图层次结构下的某个组件访问它,则需要将 ref 作为属性向下传递,或者将回调方法作为属性向下传递,并在抽屉父组件级别上定义。 - kzzzf