[英]@mui/system -- how to pass transient props to styled()
我正在使用import { styled } from "@mui/system"
; 像這樣:
const Column = styled("div")<ColumnProps>`
background: ${(props) => props.backgroundColor ?? "blue"};
`;
export default function App() {
return (
<div>
<Column backgroundColor={"green"}>column</Column>
</div>
);
它產生以下錯誤:
Warning: React does not recognize the `backgroundColor` prop on a DOM element.
我怎樣才能通過這樣的道具而不觸發這樣的錯誤? styled-components 具有“transient-props”,可以使用 $ 調用,但不適用於 @mui/system
在 Emotion 中,這是通過shouldForwardProp
處理的。
這是您的沙盒的修改版本:
import { styled } from "@mui/system";
type ColumnProps = {
backgroundColor?: string;
};
const Column = styled("div", {
shouldForwardProp: (prop) => prop !== "backgroundColor"
})<ColumnProps>`
background: ${(props) => props.backgroundColor ?? "blue"};
`;
export default function App() {
return (
<div>
<Column backgroundColor={"green"}>column</Column>
</div>
);
}
MUI 文檔: https://mui.com/system/styled/#heading-styled-component-options-styles-component
我為此使用實用程序 function,所以我總是正確輸入道具名稱:
export const shouldForwardProp = <CustomProps extends Record<string, unknown>>(
props: Array<keyof CustomProps>,
prop: PropertyKey,
): boolean => !props.includes(prop as string);
const MyComponent = styled('div', {
shouldForwardProp: (prop) => shouldForwardProp<MyComponentProps>(['isDisabled', 'bgColor'], prop),
})<MyComponentProps>(({ theme, isDisabled, size, bgColor }) => ({
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.