[英]React add custom property to component
我正在嘗試創建 MUI 組件的變體。 這一切都很好,直到我運行構建命令,然后它失敗了。 我對此有一些變體,但基本上我只想要一個自定義屬性或屬性來更改組件的某些元素。
// RoundBox.js
import { styled } from "@mui/material/styles";
import MuiBox from "@mui/material/Box";
export const RoundBox = styled(MuiBox)(({roundish }) => ({
borderRadius: roundish ? 5 : 15
}));
在另一個文件中使用該組件,如下所示:
<RoundBox>
... rounded content ...
</RoundBox>
<RoundBox roundish>
... very rounded content ...
</RoundBox>
當我在開發人員模式下運行它時,這會正確呈現,但是,當我嘗試構建它時,我會收到如下錯誤:
Type error: Type 'true' is not assignable to type 'ResponsiveStyleValue<MinWidth<string | number> | MinWidth<string | number>[] | undefined> | ((theme: Theme) => ResponsiveStyleValue<MinWidth<...> | MinWidth<...>[] | undefined>)'.
我是從 memory 寫的,但是您需要告訴編譯器您期望的道具類型:
type RoundBoxProps = {
roundish: boolean
}
export const RoundBox = styled<RoundBoxProps>(MuiBox)(({ roundish }) => ({
borderRadius: roundish ? 5 : 15
}));
如果您只期望一些道具,您也可以通過內聯類型來簡化它:
export const RoundBox = styled<{ roundish: boolean }>(MuiBox)(({ roundish }) => ({
borderRadius: roundish ? 5 : 15
}));
你可以這樣做
const RoundBox = styled(MuiBox)(({roundish}: {roundish: boolean}) => ({
borderRadius: roundish ? 5 : 15
}));
或者
<MuiBox sx={{ borderRadius: 5 }} />
<MuiBox sx={{ borderRadius: 15 }} />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.