4 回答

TA貢獻1936條經驗 獲得超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>
? );
}

TA貢獻1963條經驗 獲得超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;
}
`;

TA貢獻2011條經驗 獲得超2個贊
通過在StyledButton中添加className,可以覆蓋MUI按鈕樣式,
<StyledButton className={'myclassName'}>Hello</styledButton>
const StyledButton = styled(Button)`
&.myclassName {
background-color: red,
border-radius: 0
}
`;

TA貢獻1765條經驗 獲得超5個贊
const StyledButton = styled(Button)({
'&&&': {
backgroundColor: red,
borderRadius: 0
}
)}
- 4 回答
- 0 關注
- 175 瀏覽
添加回答
舉報