JuM*_*Gar 7 css ecmascript-6 reactjs material-ui
我有这个代码:
<Drawer
docked = {false}
width = {330}
open = {this.state.drawerOpen}
onRequestChange = {(drawerOpen) => this.setState({drawerOpen})}
>
<MenuItem primaryText="Inicio" onTouchTap = {this.drawerOpened} containerElement = {<Link to="/administrador/inicio"/>}/>
<MenuItem primaryText="Nueva Incidencia" onTouchTap = {this.drawerOpened} containerElement = {<Link to="/administrador/nueva_incidencia"/>}/>
<MenuItem primaryText="Incidencias Recibidas" onTouchTap = {this.drawerOpened} containerElement = {<Link to="/administrador/incidencias_recibidas"/>}/>
<MenuItem primaryText="Informes" /*onTouchTap = {() => this.currentPages('Informes')}*/onTouchTap = {this.drawerOpened} containerElement = {<Link to="/administrador/informes"/>}/>
</Drawer>
Run Code Online (Sandbox Code Playgroud)
我希望当我点击一个 MenuItem 时,它设置为“活动”(如在 Bootstrap 中),背景为浅灰色和类似的样式。我怎么能这样做?问题也是由于 React-Router,它卸载组件 Menu 并再次重新渲染它,因此状态不可用。
谢谢你。
在更新版本的 Material UI(当然在 v4 中)中,您可以使用该selected属性,例如这是我的<ListItemLink>组件,我使用的是 ListItem 组件,但也适用于 MenuItem。请注意该行selected={to === location.pathname}:
import PropTypes, { InferProps } from 'prop-types'
import React from 'react'
import { Link, useParams, useLocation } from 'react-router-dom'
function ListItemLink({ disabled = false, icon, primary, to }: InferProps<typeof ListItemLink.propTypes>) {
const location = useLocation()
const renderLink = React.useMemo(
() => React.forwardRef<HTMLAnchorElement>((itemProps, ref) => <Link to={to} ref={ref} {...itemProps} />),
[to],
)
return (
<ListItem
button
selected={to === location.pathname}
disabled={disabled ?? false}
component={renderLink}
>
{icon ? <ListItemIcon>{icon}</ListItemIcon> : null}
<ListItemText primary={primary} />
</ListItem>
)
}
ListItemLink.propTypes = {
icon: PropTypes.element,
primary: PropTypes.string.isRequired,
to: PropTypes.string.isRequired,
disabled: PropTypes.bool
}
ListItemLink.defaultProps = {
disabled: false
}
Run Code Online (Sandbox Code Playgroud)
如果在某个时候,您想自定义默认的选定样式,只需在创建主题时覆盖它:
import { createMuiTheme } from '@material-ui/core/styles'
import { colors } from '@material-ui/core'
const theme = createMuiTheme({
overrides: {
MuiListItem: {
root: {
"&$selected": {
color: colors.blue[500],
backgroundColor: colors.lightBlue[100]
}
}
}
}
})
export default theme
Run Code Online (Sandbox Code Playgroud)
这是我的解决方法:
定义函数:
isActive = (value) => (location.pathname === value ? 'active' : '')
<MenuItem primaryText="Inicio" onTouchTap = {this.drawerOpened}
className={this.isActive('/administrador/inicio')}
containerElement = {<Link to="/administrador/inicio"/>}/>
Run Code Online (Sandbox Code Playgroud)
现在你只是缺少'active'的de css样式。
如何围绕 MenuItem 创建一个包装组件并接受样式属性,然后将其应用到 MenuItem?
这可能会进一步帮助: Togglebackgroundcoloroflistonclickreact.js
| 归档时间: |
|
| 查看次数: |
7474 次 |
| 最近记录: |