gpt4 book ai didi

typescript - 如何防止将 Prop 传递给内部样式组件

转载 作者:行者123 更新时间:2023-12-05 09:03:17 25 4
gpt4 key购买 nike

我正在尝试在 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 lowercase iseven 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};
}
`,
);

注意:shouldForwardPropsskipSx 如果你想阻止 sx 和其他 Prop , Prop 没有完全对齐同时 Prop 。
有关详细信息,请参阅 this github issue

关于typescript - 如何防止将 Prop 传递给内部样式组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70102062/

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