Material-UI Drawer 组件的单独触发器
Posted
技术标签:
【中文标题】Material-UI Drawer 组件的单独触发器【英文标题】:Separate trigger for Material-UI Drawer Component 【发布时间】:2018-09-14 19:55:29 【问题描述】:如果我有一个 material-ui Drawer
组件,我如何使用与抽屉本身分开的元素来切换该状态?在所有示例中,他们都使用如下内容:
export class DrawerSimpleExample extends React.Component
constructor(props)
super(props);
this.state = open: false;
handleToggle = () => this.setState(open: !this.state.open);
render()
return (
<MuiThemeProvider muiTheme=customTheme>
<div>
<RaisedButton
label="Toggle Drawer"
onClick=this.handleToggle
/>
<Drawer open=this.state.open
docked=true
>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item 2</MenuItem>
</Drawer>
</div>
</MuiThemeProvider>
);
但是如果我想让RaisedButton
出现在AppBar
中呢?像这样:
export class AppBarExampleIconButton extends React.Component
constructor(props)
super(props);
render()
return (
<MuiThemeProvider muiTheme=customTheme>
<AppBar
title=<span style=styles.title>Title</span>
onTitleClick=handleClick
iconElementLeft=<div>
<IconButton><NavigationMenu /></IconButton>
// Have this button toggle the drawer instead
<RaisedButton
label="Toggle Drawer"
onClick=this.handleToggle
/>
</div>
iconElementRight=<FlatButton label="Save" />
/>
</MuiThemeProvider>
);
此外,如果我想让Drawer
永久打开,但仍可从AppBar
切换(我将在打开/关闭时调整它们的位置/宽度)怎么办。
【问题讨论】:
【参考方案1】:用道具而不是状态切换抽屉。
export class AppBarExampleIconButton extends React.Component
constructor(props)
super(props);
this.state =
openDrawer: false,
handleToggle=()=>this.setState(openDrawer: !this.state.openDrawer);
render()
return (
<MuiThemeProvider muiTheme=customTheme>
<AppBar
title=<span style=styles.title>Title</span>
onTitleClick=handleClick
iconElementLeft=<div>
<IconButton><NavigationMenu /></IconButton>
// Have this button toggle the drawer instead
<RaisedButton
label="Toggle Drawer"
onClick=this.handleToggle
/>
</div>
iconElementRight=<FlatButton label="Save" />
/>
<DrawerSimpleExample open = this.state.openDrawer/>
</MuiThemeProvider>
);
在您的 DrawerSimple 组件中:
export class DrawerSimpleExample extends React.Component
render()
return (
<MuiThemeProvider muiTheme=customTheme>
<div>
<Drawer open=this.props.open
docked=true>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item 2</MenuItem>
</Drawer>
</div>
</MuiThemeProvider>
);
【讨论】:
以上是关于Material-UI Drawer 组件的单独触发器的主要内容,如果未能解决你的问题,请参考以下文章
样式化 Material-UI Drawer 组件与 Styled Components
Material UI - 在 AppBar 点击打开 LeftNav / Drawer