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

Fre*_*eez 4 reactjs material-ui

我想material-ui在这样的组件中使用我的主题中的颜色:

const MyComponent = props => (
   <UsersIcon color={currentTheme.primary1Color} />
)
Run Code Online (Sandbox Code Playgroud)

所以,我需要从当前提供的主题中提取一个值。

我找到了解决这种情况的有效解决方案,使用上下文来检索当前主题:

const MyComponent = (props, {muiTheme}) => (
    <UsersIcon color={muiTheme.palette.primary1Color} />
)
contextTypes = {
    muiTheme: PropTypes.object.isRequired,
}
Run Code Online (Sandbox Code Playgroud)

React上下文使用“引擎盖下” material-ui,所以我的解决方案是不是面向未来-的执行MUI可以改变- ,有没有办法在适当的(或推荐)的方式来解决这个问题?

Spa*_*atz 8

您可以使用reacthookhigher-order组件访问主题变量。

带钩子的例子:

//...
import { useTheme } from '@material-ui/core/styles';

const MyComponent = () => {
    const theme = useTheme();
    return <UsersIcon color={theme.palette.primary.main} />
}
Run Code Online (Sandbox Code Playgroud)

使用 HOC 的示例:

//...
import { withTheme } from '@material-ui/core/styles';

const MyComponent = ({theme, ...other}) => {
    return <UsersIcon color={theme.palette.primary.main} />
}

export default withTheme(MyComponent)
Run Code Online (Sandbox Code Playgroud)

不要忘记用包装根应用程序组件 ThemeProvider

提到另一种方法是makeStylesCSS-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} />
}

Run Code Online (Sandbox Code Playgroud)


yko*_*ach 3

是的,你有!使用 muiThemeable..

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

来自material-ui 文档