[英]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.