[英]Can I override Material-UI with css modules in create-react-app v2?
For example I want to add margin-top to this button例如我想给这个按钮添加 margin-top
import classes from 'button.module.css';
<Button
type="submit"
variant="contained"
color="primary"
fullWidth
disabled={this.props.isLoading}
className={classes.Button}
>
{this.props.isLoading ? <CircularProgress size={20}/> : 'SIGN IN'}
</Button>
In button.module.css file在 button.module.css 文件中
.Button {
margin-top: 15px;
}
Is this possible to use this method instead of override like instruction in official material-ui page?是否可以使用此方法而不是像官方 material-ui 页面中的指令那样覆盖?
Yes, you can.是的你可以。
Use className
like you normally you do with CRA.像通常使用 CRA 一样使用
className
。
This will explain how to use CSS modules.这将解释如何使用 CSS 模块。 This is straightforward.
这很简单。
However, after doing the above-mentioned thing, I had an issue of my CSS getting overridden by MaterialUI CSS.但是,在完成上述操作后,我遇到了 CSS 被 MaterialUI CSS 覆盖的问题。 So we need to change the order of Styleinjection.
所以我们需要改变Styleinjection的顺序。
Simply use StylesProvider
component with the injectFirst
property:只需将
StylesProvider
组件与injectFirst
属性一起使用:
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import { StylesProvider } from "@material-ui/core/styles" // <-- import this component, and wrap your App.
ReactDOM.render(
<StylesProvider injectFirst>
<App />
</StylesProvider>,
document.getElementById('root')
)
It's a problem of CSS specificity, in which your CSS is loaded before the Material UI's styles, and therefore is overridden by them.这是 CSS 特定性的问题,其中您的 CSS 在 Material UI 的样式之前加载,因此被它们覆盖。 As stated in the docs , regarding the
injectFirst
property:如文档中所述,关于
injectFirst
属性:
By default, the styles are injected last in the element of the page.
默认情况下,样式最后注入到页面元素中。 As a result, they gain more specificity than any other style sheet.
因此,它们比任何其他样式表获得更多的特异性。 If you want to override Material-UI's styles, set this prop.
如果要覆盖 Material-UI 的样式,请设置此属性。
In my recent project i did things like在我最近的项目中,我做了类似的事情
import './style.css';
where this is example content of style.css这是 style.css 的示例内容
.detailbox-paper {
width: 90vw;
margin: 20px auto 0px auto;
}
where i consumed it by using a className on the element like this <Paper className="detailbox-paper">
and it worked.我通过在元素上使用 className 来使用它,例如
<Paper className="detailbox-paper">
并且它起作用了。 One thing to keep in mind by this approach, is the css specificity you are then starting to fight with.通过这种方法要记住的一件事是,您将开始与之抗争的 css 特异性。
You can also use inline styles={{}}
with the camelCase syntax for attributes.您还可以将内联
styles={{}}
与属性的驼峰式语法一起使用。 But, as far as i know, inline styles always will be set, exept there is the !important
keyword.但是,据我所知,内联样式总是会被设置,除非有
!important
关键字。
Hopefully this could help you on your journey.希望这对您的旅程有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.