gpt4 book ai didi

javascript - 如何从祖先覆盖嵌套 Material UI 组件的样式?

转载 作者:行者123 更新时间:2023-12-03 19:42:53 24 4
gpt4 key购买 nike

我正在使用来自外部库的组件,该组件不允许我更改其大部分样式,但我想更改作为 Material ui 按钮的按钮的样式,在检查元素时它清楚地显示类 MuiButtonBase -root MuiIconButton-root MuiIconButton-colorInherit

例如,如何覆盖 MuiIconButton-root 样式?这是我的组件:

class MyComponent extends Component {

render() {
const { classes } = this.props;
return (
<div className={classes.myComponent}>
<3rdPartyComponent />
</div>
);

}
}


export default withStyles(styles)(MyComponent)

我尝试如下声明我的样式函数,但没有成功:
const styles = theme => ({
myComponent: {
"&.MuiIconButton-root": {
padding: "0px"
}
}
});

有谁能够帮我?提前致谢。

最佳答案

假设为 myComponent 生成的类名是 myComponent-jss123 .您在样式中使用的选择器 ( &.MuiIconButton-root ) 将等同于 .myComponent-jss123.MuiIconButton-root这将匹配任何具有 的元素两个这些类适用于它。我相信您的意图是匹配 的图标按钮子孙div您在其上应用 myComponent类(class)。在这种情况下,您需要使用 descendant combinator由空格表示,因此适当的样式如下所示:

const styles = theme => ({
myComponent: {
"& .MuiIconButton-root": {
padding: 0
}
}
});

这是一个完整的工作示例:
import React from "react";
import IconButton from "@material-ui/core/IconButton";
import DeleteIcon from "@material-ui/icons/Delete";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
myComponent: {
"& .MuiIconButton-root": {
padding: 0
}
}
});
const ThirdPartyComponent = () => {
return (
<div>
I'm a third party component that contains an IconButton:
<IconButton color="primary">
<DeleteIcon />
</IconButton>
</div>
);
};
export default function App() {
const classes = useStyles();
return (
<div className={classes.myComponent}>
<ThirdPartyComponent />
</div>
);
}

Edit target descendant icon button

相关文档:
  • https://cssinjs.org/jss-plugin-nested/?v=v10.0.4#use--to-reference-selector-of-the-parent-rule
  • https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors
  • https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator
  • 关于javascript - 如何从祖先覆盖嵌套 Material UI 组件的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60505479/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com