使用样式组件覆盖 material-ui 按钮样式

Per*_*tyy 7 html css reactjs material-ui styled-components

我正在使用 amaterial-ui button并尝试通过样式组件覆盖边界半径(即,使其为 0)。但是,它不起作用。

代码:

import React from "react";
import styled from "styled-components";
import { Button } from "@material-ui/core";

const StyledButton = styled(Button)`
  background-color: #d29d12;
  border-radius: 0;
`;

export default function App() {
  return <StyledButton>Hello</StyledButton>;
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*ell 7

默认情况下,Material-UI 在<head>元素的末尾注入它的样式。这意味着它的样式将出现由 styled-components 生成的样式之后,因此当CSS 特异性相同时,Material-UI 样式将胜过 styled-components 样式。

您可以使用StylesProvider带有injectFirst属性的组件将 Material-UI 样式移动到 的开头,<head>然后 styled-components 样式将在它之后并获胜。

import React from "react";
import styled from "styled-components";
import Button from "@material-ui/core/Button";
import { StylesProvider } from "@material-ui/core/styles";

const StyledButton = styled(Button)`
  background-color: red;
  border-radius: 0;
`;

export default function App() {
  return (
    <StylesProvider injectFirst>
      <div className="App">
        <StyledButton>Hello</StyledButton>
      </div>
    </StylesProvider>
  );
}
Run Code Online (Sandbox Code Playgroud)

编辑样式组件

相关回答:


小智 6

使用 styled-components 更高特异性语法: https://styled-components.com/docs/faqs#how-can-i-override-styles-with-higher-specificity

const StyledButton = styled(Button)`
  && {
    background-color: red;
    border-radius: 0;
  }
`;
Run Code Online (Sandbox Code Playgroud)


小智 -5

您可以通过将 !important 应用于样式组件来覆盖按钮的默认边框半径。

const StyledButton = styled(Button)`
  borderRadius: 0px !important;
`;
Run Code Online (Sandbox Code Playgroud)