简体   繁体   English

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

[英]material-ui : Extract color from theme

I want to use a color from my material-ui theme inside a component like that :我想在这样的组件中使用我的material-ui主题中的颜色:

const MyComponent = props => (
   <UsersIcon color={currentTheme.primary1Color} />
)

So, my need is to extract a value from the current provided theme.所以,我需要从当前提供的主题中提取一个值。

I found a working solution to solve this case, using context to retrieve the current theme :我找到了解决这种情况的有效解决方案,使用上下文来检索当前主题:

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

The React context is used "under the hood" by material-ui , so my solution is not future proof – the implementation of MUI can change –, is there any way to solve this in a proper (or recommended) way ?React上下文使用“引擎盖下” material-ui ,所以我的解决方案是不是面向未来-实施MUI可以改变- ,有没有办法在适当的(或推荐)的方式来解决这个问题?

You can access the theme variables with react hook or with higher-order component.您可以使用react hookhigher-order组件访问主题变量。

Example with hook:带钩子的例子:

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

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

Example with HOC:使用 HOC 的示例:

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

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

export default withTheme(MyComponent)

Don't forget to wrap root application component with ThemeProvider不要忘记用ThemeProvider包装根应用程序组件

Another method to mention is makeStyles for CSS-in-JS styling:另一个要提及的方法是用于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} />
}

Yes you have!是的,你有! using muiThemeable..使用 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来自 material-ui 文档

If your colors don't change at runtime, you can store these constants in a global object that gets used to initialize the theme as well as used in your custom components.如果您的颜色在运行时没有改变,您可以将这些常量存储在一个全局对象中,该对象用于初始化主题以及在您的自定义组件中使用。 This would allow you to not depend on context while keeping your code dry.这将允许您在保持代码干燥的同时不依赖上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM