【问题标题】:Material ui button does not take into consideration the css styles to override the default oneMaterial ui按钮不考虑css样式来覆盖默认样式
【发布时间】:2021-01-23 19:31:25
【问题描述】:

我在我的 react 应用程序中使用了私有引导 css 样式。我想用引导样式更新默认材质 ui 组件的样式。

import React, {useState} from 'react';
import 'cg-bootstrap/core/build/cg-bootstrap-standard.css'

const Sample = () => {
const [value, setValue]= useState('');

const handleChange = (e:React.ChangeEvent<HTMLInputElement> ) => {
        setValue(e.target.value);
    }
return (
<Grid container justify="center" alignItems="center">

<Grid item>
<Typography>Label text</Typogrpahy>
</Grid>
<Grid item>
<TextField value={state.value} variant="contained" onChange={handleChange}/>
</Grid>
<Grid item>
<Button 
variant="contained"
type="submit"
classes={{
contained: "btn btn-md btn-primary",
}}>
Submit
</Button>
</Grid>
</Grid>
)
}

cg-bootstrap-standard.css

.btn-primary {
  color: #fff;
  background-color: black;
  border-color: black; }
  .btn-primary:hover {
    color: #fff;
    background-color: black;
    border-color: black; }
  .btn-primary:focus, .btn-primary.focus {
    color: #fff;
    background-color: black;
    border-color: black;
    -webkit-box-shadow: 0 0 0 0.125rem rgba(38, 38, 38, 0.5);
    box-shadow: 0 0 0 0.125rem rgba(38, 38, 38, 0.5); }
  .btn-primary.disabled, .btn-primary:disabled {
    color: #fff;
    background-color: black;
    border-color: black; }
  .btn-primary:not(:disabled):not(.disabled):active, .btn-primary:not(:disabled):not(.disabled).active,
  .show > .btn-primary.dropdown-toggle {
    color: #fff;
    background-color: black;
    border-color: black; }
    .btn-primary:not(:disabled):not(.disabled):active:focus, .btn-primary:not(:disabled):not(.disabled).active:focus,
    .show > .btn-primary.dropdown-toggle:focus {
      -webkit-box-shadow: 0 0 0 0.125rem rgba(38, 38, 38, 0.5);
      box-shadow: 0 0 0 0.125rem rgba(38, 38, 38, 0.5); }

当我查看 chrome 控制台时,我得到了:

btn btn-primary 样式已被覆盖,我想将它们的样式应用为应用于按钮的最终样式,而不是 material-ui 的默认样式。我该如何解决?

【问题讨论】:

    标签: javascript css reactjs bootstrap-4 material-ui


    【解决方案1】:

    你可以使用 StylesProvider 和 prop injectFirst

    StylesProvider 组件有一个 injectFirst 属性来注入 样式标签在头部(优先级较低)

    import { Button, StylesProvider } from "@material-ui/core";
    
    function Sample() {
      return (
        <StylesProvider injectFirst>
          {/* Your component tree */}
          <Button
            variant="contained"
            classes={{ contained: "btn btn-md btn-primary" }}
          >
            Hello
          </Button>
        </StylesProvider>
      );
    }
    

    默认情况下,MUI 将其样式表作为&lt;head&gt; 标签的最后一个元素注入,因此它的优先级高于您的 Bootstrap 样式表。上述解决方案应该可以解决这种情况。

    https://material-ui.com/styles/advanced/#css-injection-order

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-27
      • 2020-01-30
      • 2019-03-07
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 2011-09-06
      • 2020-08-10
      相关资源
      最近更新 更多