在Material-UI 4中,可以轻松创建可在组件内部使用的样式。我为此使用makeStyles()
函数。
const useStyles = makeStyles((theme: Theme) => ({
hoverableContent: {
color: theme.palette.primary.contrastText,
backgroundColor: theme.palette.primary.main,
'&:hover': {
backgroundColor: theme.palette.primary.dark
}
}
}));
const MyComponent = () => {
const classes = useStyles();
...
}
但是,我想在多个组件中重用此样式。在Material-Ui 4中执行此操作的最佳方法是什么?
注意:我认为这是一个更高层次的抽象:共享抽象类(以受控方式),而不只是颜色(在主题中)。
答案 0 :(得分:1)
您可以执行以下任一操作:
const styles = (theme: Theme) => ({
hoverableContent: {
color: theme.palette.primary.contrastText,
backgroundColor: theme.palette.primary.main,
'&:hover': {
backgroundColor: theme.palette.primary.dark
}
}
})
然后这种方法导致了这个问题。如何合并多种样式? https://github.com/mui-org/material-ui/issues/11517
答案 1 :(得分:1)
我知道这有点晚了,但是我只是面对它并通过制作钩子解决了:
// someSharedClasses.ts
export default makeStyles((theme)=>createStyles({
hoverableContent: {
color: theme.palette.primary.contrastText,
backgroundColor: theme.palette.primary.main,
'&:hover': {
backgroundColor: theme.palette.primary.dark
}
}
}));
和其他组件:
import useSharedClasses from './someSharedClasses.ts';
const MyComponent = () => {
const sharedClasses = useSharedClasses();
// use sharedClasses.hoverableContent as className
}