我正在尝试在 Material UI 组件之上进行合成,通过给定的 Prop 仅更改样式。
import { Typography } from "@mui/material";
import { styled } from "@mui/system";
type MyTypographyExtraProps = { isEven?: boolean };
export const MyTypography = styled(Typography)<MyTypographyExtraProps>(
({ theme, isEven }) => `
color: ${theme.palette.common.black};
::after {
content: "";
display: inline-block;
height: ${theme.spacing(2)};
width: ${theme.spacing(2)};
border-radius: ${theme.spacing(2)};
background-color: ${theme.palette[isEven ? "success" : "error"].main};
}
`,
);
样式化函数将我的 isEven
属性传递给 Material Typography 组件,而 Typography 将它传递给 DOM,所以我收到了警告
Warning: React does not recognize the
isEven
prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercaseiseven
instead. If you accidentally passed it from a parent component, remove it from the DOM element.
如何在传递给排版元素之前省略类型?
我可以制作另一个组件并消除该层中的 Prop ,但我很想知道有没有办法在没有额外组件的情况下做到这一点。
最佳答案
Material docs建议一个函数来消除传递的 Prop 。
shouldForwardProp:说明哪些属性必须传递给给定样式的组件。
export const MyTypography = styled(MuiTypography, {
shouldForwardProp: prop => prop !== "isEven", // ⭐
})<MyTypographyExtraProps>(
({ theme, isEven }) => `
color: ${theme.palette.common.black};
::after {
content: "";
display: inline-block;
height: ${theme.spacing(2)};
width: ${theme.spacing(2)};
border-radius: ${theme.spacing(2)};
background-color: ${theme.palette[isEven ? "success" : "error"].main};
}
`,
);
注意:shouldForwardProps
和 skipSx
如果你想阻止 sx
和其他 Prop , Prop 没有完全对齐同时 Prop 。
有关详细信息,请参阅 this github issue
https://stackoverflow.com/questions/70102062/