material-ui : Extract color from theme

天大地大妈咪最大 提交于 2019-12-12 03:44:03

问题


I want to use a color from my material-ui theme inside a component like that :

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 ?


回答1:


Yes you have! using 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




回答2:


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.



来源:https://stackoverflow.com/questions/43169520/material-ui-extract-color-from-theme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!