我有一个具有组件基础结构的移动应用程序。为了全局展示抽屉,我已经在我的 Home.js 中实现了它,如下面的代码,但我的抽屉切换器必须位于我的容器组件内的Header组件中。
如何将主抽屉的实例发送到标题组件并控制开/关状态?
Home.js代码:
class Home extends Component {
render() {
const drawerContent = <DrawerComp />;
return (
<Drawer
ref={comp => {
this.drawer = comp;
}}
drawerWidth={250}
drawerContent={drawerContent}
type={Drawer.types.Overlay}
drawerPosition={Drawer.positions.Right}
maskAlpha={0.05}
onDrawerOpen={() => {
console.log("Drawer is opened !");
}}
onDrawerClose={() => {
console.log("Drawer is closed !");
this.props.dispatch(displayDrawer());
}}
>
<Container>
<StatusBar barStyle="light-content" />
<Header drawer={this.drawer} />
<TouchableHighlight
underlayColor="#118d95"
onPress={this.handleDisplayDrawer}
>
<Text>Open Right Drawer</Text>
</TouchableHighlight>
</Container>
</Drawer>
);
}
}
标题组件:
class Header extends Component {
handleDisplayDrawer = () => {
//
};
render() {
return (
<View style={styles.container}>
<TouchableHighlight
onPress={this.handleDisplayDrawer}
style={styles.colSmall}
underlayColor="#ffffff"
>
<Image
style={styles.icon}
resizeMode="contain"
source={require("./images/icon-menu.png")}
/>
</TouchableHighlight>
</View>
);
}
}
答案 0 :(得分:1)
将函数传递给Header
组件,该组件在需要时调用该函数。
class Home extends Component {
toggleDrawer = () => {
this.drawer.toggle(); // edit this according to drawer library
}
render() {
<Header onMenuPress={this.toggleDrawer} />
}
}
class Header extends Component {
render() {
<TouchableHighlight onPress={this.props.onMenuPress}>
<Image />
</TouchableHighlight>
}
}
答案 1 :(得分:0)
您可以在Drawer.js中编写setDrawerState函数。这实际上关闭了抽屉。像
这样的东西setDrawerState(isOpen) => {
this.setState({
isOpen,
})
}
In Your home.js , you already have ref to drawer component .
you can write following function.
close = () => {
this.drawer.setDrawerState(false)
}
open = () => {
this.drawer.setDrawerState(true)
}
<Header
close={this.close}
open={this.open}
/>
答案 2 :(得分:0)
我一直在努力寻找解决方案,因此,如果您使用自定义标题组件,那么我的建议是在每个屏幕中呈现客户标题并使用以下方法进行切换:-
navigation.openDrawer();