[英]material-ui : Extract color from theme
我想在这样的组件中使用我的material-ui
主题中的颜色:
const MyComponent = props => (
<UsersIcon color={currentTheme.primary1Color} />
)
所以,我需要从当前提供的主题中提取一个值。
我找到了解决这种情况的有效解决方案,使用上下文来检索当前主题:
const MyComponent = (props, {muiTheme}) => (
<UsersIcon color={muiTheme.palette.primary1Color} />
)
contextTypes = {
muiTheme: PropTypes.object.isRequired,
}
该React
上下文使用“引擎盖下” material-ui
,所以我的解决方案是不是面向未来-实施MUI
可以改变- ,有没有办法在适当的(或推荐)的方式来解决这个问题?
您可以使用react 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
包装根应用程序组件
另一个要提及的方法是用于CSS-in-JS
样式的makeStyles
:
//...
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} />
}
是的,你有! 使用 muiThemeable ..
import muiThemeable from 'material-ui/styles/muiThemeable';
const MyComponent = props => (
<UsersIcon color={props.muiTheme.palette.primary1Color} />
)
export default muiThemeable()(MyComponent )
如果您的颜色在运行时没有改变,您可以将这些常量存储在一个全局对象中,该对象用于初始化主题以及在您的自定义组件中使用。 这将允许您在保持代码干燥的同时不依赖上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.