如何从父组件调用 DrawerLayoutAndroid 上的 openDrawer 函数?

How do I call the openDrawer function on DrawerLayoutAndroid from parent component?

我制作了一个组件来设置 DrawerLayoutAndroid,我想在我的索引文件中调用它。

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 结束。

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();
    }
}

这给了我错误 "undefined is not an object (evaluating 'this.refs.menudrawer.openDrawer')"。

我该如何解决这个问题?

谢谢

看起来不错,您只是错误地访问了菜单抽屉。应该是:

this.menudrawer.openDrawer();

因为你的参考是:

ref={(_menudrawer) => this.menudrawer = _menudrawer}