我已经创建了一个需要具有自定义样式的组件,因此我使用了createStyles({})
。这似乎已经(几乎)如我所愿。我还使用了createGenerateClassName({})
来表示我需要确定性的样式名称。但是,两者似乎并没有协同工作。尽管标准MUI组件不再将哈希号作为类名的一部分,但是自定义样式却具有。需要更改什么以支持每个类名称的确定性样式?
这是我的代码:
import {Component, ComponentMeta, ComponentProps, SizeObject} from '@xyz/abc' // real name removed here due to restrictions
import {Button, Paper} from '@material-ui/core'
import {createGenerateClassName, createStyles, MuiThemeProvider, Theme, withStyles} from '@material-ui/core/styles'
import JssProvider from 'react-jss/lib/JssProvider'
const theme = createMuiTheme({
palette: {
primary: {
main: 'blue',
},
secondary: {
main: 'green',
},
error: {
main: 'red',
},
},
typography: {
useNextVariants: true,
},
})
const styles = ({palette, spacing}: Theme) =>
createStyles({
button: {
backgroundColor: '#2196f3',
},
buttonDark: {
backgroundColor: '#880e4f',
},
buttonLight: {
backgroundColor: '#e1bee7',
},
})
const generateClassName = createGenerateClassName({
dangerouslyUseGlobalCSS: true,
})
class AnalysisSelector extends Component<ComponentProps, any> {
render() {
const {classes} = this.props
return (
<MuiThemeProvider theme={theme}>
<JssProvider generateClassName={generateClassName}>
<Paper {...this.props.emit()} className={'paperContainer'}>
<Button className={classes.button}>Primary Light</Button>
<Button className={classes.buttonLight}>Primary</Button>
<Button className={classes.buttonDark}>Primary Dark</Button>
</Paper>
</JssProvider>
</MuiThemeProvider>
)
}
}
export const MNOAnalysisSelector = withStyles(styles, {name: 'mnoButton'})(AnalysisSelector)
最后是呈现的HTML:
<button class="MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-flat mnoButton-button-1" tabindex="0" type="button">
<span class="MuiButton-label">Primary Light</span>
<span class="MuiTouchRipple-root"></span>
</button>
<button class="MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-flat mnoButton-buttonLight-3" tabindex="0" type="button">
<span class="MuiButton-label">Primary</span>
<span class="MuiTouchRipple-root"></span>
</button>
<button class="MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-flat mnoButton-buttonDark-2" tabindex="0" type="button">
<span class="MuiButton-label">Primary Dark</span>
<span class="MuiTouchRipple-root"></span>
</button>
</div>
我很好,因为类名分别为mnoButton-button
,mnoButton-buttonLight
和mnoButton-buttonDark
,我只需要删除结尾的哈希即可。
感谢您的任何建议/帮助。
答案 0 :(得分:1)
您可以使用第4版中记录的全局类名:https://next.material-ui.com/styles/advanced/#jss-plugin-global
jss-plugin-global也包含在v3中,因此可以使用相同的方法。
用于创建全局名称的其他语法的only way是如果传递给name
的{{1}}以“ Mui”开头(我不建议这样做)。
我在下面的代码中展示了这两种方法。
withStyles
答案 1 :(得分:0)
来源:github
import { StylesProvider, createGenerateClassName } from '@material-ui/core/styles';
// other imports
const generateClassName = (rule, styleSheet) =>
`${styleSheet.options.classNamePrefix}-${rule.key}`;
test(deterministic classnames, () => {
render(
<StylesProvider generateClassName={generateClassName}>
<App />
</StylesProvider>
);
});