簡體   English   中英

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 ,所以我的解決方案是不是面向未來-實施MUI可以改變- ,有沒有辦法在適當的(或推薦)的方式來解決這個問題?

您可以使用react 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包裝根應用程序組件

另一個要提及的方法是用於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 )

來自 material-ui 文檔

如果您的顏色在運行時沒有改變,您可以將這些常量存儲在一個全局對象中,該對象用於初始化主題以及在您的自定義組件中使用。 這將允許您在保持代碼干燥的同時不依賴上下文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM