材质ui按钮未考虑css样式来覆盖默认样式

时间:2020-10-08 17:33:14

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

我在我的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控制台上查看时,我得到了: transpiled compoenent

styles

styles1

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

1 个答案:

答案 0 :(得分:1)

您可以将StylesProvider与道具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将其样式表作为<head>标签的最后一个元素来注入,因此这就是为什么它比Bootstrap样式表具有更高的优先级的原因。以上解决方案应该可以解决这种情况。

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