我想使用我的颜色material-ui
像这样的组件内的主题:
const MyComponent = props => (
<UsersIcon color={currentTheme.primary1Color} />
)
所以,我的需要是从当前提供的主题中提取一个值。
我找到了一个可行的解决方案来解决这种情况,使用上下文来检索当前主题:
const MyComponent = (props, {muiTheme}) => (
<UsersIcon color={muiTheme.palette.primary1Color} />
)
contextTypes = {
muiTheme: PropTypes.object.isRequired,
}
The React
上下文是在“幕后”使用的material-ui
,所以我的解决方案不是面向未来的——实施MUI
可以改变 - 有什么方法可以以正确(或推荐)的方式解决这个问题?
You can access https://material-ui.com/styles/advanced/#accessing-the-theme-in-a-component反应主题变量hook
或与higher-order
成分。
带钩子的示例:
//...
import { useTheme } from '@material-ui/core/styles';
const MyComponent = () => {
const theme = useTheme();
return <UsersIcon color={theme.palette.primary.main} />
}
HOC 示例:
//...
import { withTheme } from '@material-ui/core/styles';
const MyComponent = ({theme, ...other}) => {
return <UsersIcon color={theme.palette.primary.main} />
}
export default withTheme(MyComponent)
不要忘记将根应用程序组件包装为ThemeProvider
另一种值得一提的方法是makeStyles
for CSS-in-JS
造型:
//...
import { makeStyles } from '@material-ui/core/styles'
const useStyles = makeStyles(theme => ({
icon: {
color: theme.palette.primary.main
}
}))
const MyComponent = () => {
const classes = useStyles()
return <UsersIcon className={classes.icon} />
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)