Material UI Styled()-如何设置子组件的样式



背景

因此,我使用MaterialUI公开的styled()实用程序函数来设计我的组件的样式。假设我有一个名为Child的基本组件,我将该基本组件导入另一个React组件。现在,如果我试图再次为导入的零部件设置样式,样式将不会覆盖基本零部件样式。(但是console.log是从styled()实用程序中调用的)请参阅下面的示例:

import { styled } from "@mui/material";
function App() {
const StyledChild = styled(Child)(({ theme }) => {
console.log("called from App");
return {
backgroundColor: "black"
};
});
return <StyledChild />;
}
function Child() {
const Div = styled("div")(({ theme }) => {
console.log("called from Child");
return {
backgroundColor: "red"
};
});
return <Div>hello world</Div>;
}
export default App;

控制台结果如下:

called from App

called from Child

代码沙箱

问题

如前所述,在codesandbox示例中可以看到,仅应用了backgroundColor: 'red'的基本样式。即使记录了called from App,导入组件的backgroundColor: 'black'样式也不应用。

问题

  • 如何有效地为以前已设置样式的组件设置样式
  • 而且(只是好奇)为什么上面的解决方案不起作用,如果调用了styled()实用程序,那么样式应该由返回的obj中定义的应用程序来应用

编辑/更新

经过实验,我发现即使删除了Child的原始样式,父级别的样式仍然无法渲染。

import { styled } from "@mui/material";
function App() {
const StyledChild = styled(Child)(({ theme }) => {
console.log("called from App");
return {
backgroundColor: "black"
};
});
return <StyledChild />;
}
function Child() {
return <div>hello world</div>;
}
export default App;

结果不受父级backgroundColor: "black"的影响,因此更改问题的标题以更好地适应问题如何在父级设置子组件的样式

在尝试隔离问题几天后,我找到了问题的原因和可行的解决方案。希望,如果将来有人遇到类似的问题,他们可以通过以下方式解决。

因此,最初的问题是父母的造型不会影响孩子。问题是,在子组件中,我没有包括以下内容:function Child({ ...others }) { //function component,在组件本身内部,我需要添加{...others}作为元素的属性之一。查看完整解决方案:

import { styled } from "@mui/material";
function App() {
const StyledChild = styled(Child)(({ theme }) => {
console.log("called from App");
return {
backgroundColor: "black"
};
});
return <StyledChild />;
}
function Child({ ...others }) {
const Div = styled("div")(({ theme }) => {
console.log("called from Child");
return {
backgroundColor: "red"
};
});
return <Div { ...others }>hello world</Div>;
}
export default App;

我的最佳选择是,父样式是通过引擎盖下的类应用的(如果有人有文档链接,那将不胜感激)。这些类需要作为Child元素的属性应用。

代码沙箱解决方案

最新更新