如何通过iconStyleLeft或其他方法修改Material-UI左侧汉堡图标颜色?
解决Material-UI AppBar左侧汉堡图标颜色不生效的问题
嘿,我帮你搞定这个问题啦!在你使用的老版本Material-UI(v0.x系列)里,iconStyleLeft其实是控制左侧图标容器的样式,而非图标本身的颜色,所以直接设置颜色才没起作用。这里给你两种可靠的解决办法:
方法1:自定义左侧图标(推荐)
直接通过iconElementLeft属性替换默认的汉堡图标,同时精准设置它的颜色:
import React from 'react'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import NavigationMenu from 'material-ui/svg-icons/navigation/menu'; import {grey50, grey900 } from 'material-ui/styles/colors'; const NavBar = () => ( <div> <AppBar title="Home-pro" titleStyle={{color: grey900, textAlign: 'center'}} style={{backgroundColor: grey50}} iconElementLeft={ <IconButton> <NavigationMenu color={grey900} /> </IconButton> } /> </div> ); export default NavBar;
这种方式完全可控,你还能根据需求调整图标的大小、点击事件等其他属性。
方法2:通过嵌套样式覆盖图标颜色
如果不想替换默认图标,也可以利用CSS嵌套选择器,直接选中容器内的SVG元素来修改颜色:
import React from 'react'; import AppBar from 'material-ui/AppBar'; import {grey50, grey900 } from 'material-ui/styles/colors'; const NavBar = () => ( <div> <AppBar title="Home-pro" titleStyle={{color: grey900, textAlign: 'center'}} style={{backgroundColor: grey50}} iconStyleLeft={{ '& svg': { color: grey900 } }} /> </div> ); export default NavBar;
补充说明
之所以你的原代码没生效,是因为默认汉堡图标是独立的SVG组件,它自身的颜色样式优先级比容器的iconStyleLeft更高,所以直接给容器设颜色不会影响到内部的图标~
内容的提问来源于stack exchange,提问作者Samkit Shah
相关产品推荐
相关产品推荐

