如何从父组件调用 DrawerLayoutAndroid 上的 openDrawer 函数? [英] How do I call the openDrawer function on DrawerLayoutAndroid from parent component?
问题描述
我制作了一个组件来设置 DrawerLayoutAndroid,我想在我的索引文件中调用它.
I have made a component which sets up the DrawerLayoutAndroid, which I want to call in my index file.
drawer.js:
export default class MenuDrawer extends Component {
constructor(props) {
super(props);
this.openDrawer = this.openDrawer.bind(this);
}
render() {
var navigationView = (
// ...
);
return (
<DrawerLayoutAndroid
ref={(_drawer) => this.drawer = _drawer}
drawerWidth={200}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => navigationView}>
{this.props.children}
</DrawerLayoutAndroid>
);
}
openDrawer() {
this.drawer.openDrawer();
}
}
然后我将索引文件中的 render() 函数中的所有内容都包裹起来,因为我希望从任何地方都可以访问抽屉.我只是不知道如何从索引文件中打开抽屉.我尝试了几种不同的方法来调用该函数,但最终总是得到 undefined is not an object.
I then have everything in the render() function in my index file wrapped around since I want the drawer to be accessible from anywhere. I just cannot figure out how I open the drawer from the index file. I have tried several different ways to call the function, but I always end up getting undefined is not an object.
index.android.js
index.android.js
export default class AwesomeProject extends Component {
constructor(props) {
super(props);
this.openMenu = this.openMenu.bind(this);
}
render() {
const { region } = this.props;
return (
<MenuDrawer
ref={(_menudrawer) => this.menudrawer = _menudrawer}
style={styles.layout}>
<TouchableHighlight
style={styles.topbar}
onPress={this.openMenu}>
<Text>Open</Text>
</TouchableHighlight>
</MenuDrawer>
);
}
openMenu() {
this.refs.menudrawer.openDrawer();
}
}
这给了我错误未定义不是对象(评估'this.refs.menudrawer.openDrawer')".
This gives me the error "undefined is not an object (evaluating 'this.refs.menudrawer.openDrawer')".
我该如何解决这个问题?
How do I go about solving this?
谢谢
推荐答案
看起来不错,您只是错误地访问了 menudrawer.应该是:
It looks good, you're just accessing the menudrawer incorrectly. It should be:
this.menudrawer.openDrawer();
因为你的引用是:
ref={(_menudrawer) => this.menudrawer = _menudrawer}
这篇关于如何从父组件调用 DrawerLayoutAndroid 上的 openDrawer 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!