material-ui : 从主题中提取颜色

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使用"under the hood",所以我的解决方案不是面向未来的——MUI的实现可以改变——有什么办法以适当的(或推荐的)方式解决这个问题?

如果您的颜色在运行时不改变,您可以将这些常量存储在一个全局对象中,该对象用于初始化主题以及在您的自定义组件中使用。这将使您在保持代码干燥的同时不依赖于上下文。

是的,你有!使用 muiThemeable..

import muiThemeable from 'material-ui/styles/muiThemeable';
const MyComponent = props => (
   <UsersIcon color={props.muiTheme.palette.primary1Color} />
)
export default muiThemeable()(MyComponent )

from material-ui docs

您可以 access 主题变量与反应 hookhigher-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 用于 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} />
}