【发布时间】:2021-01-20 14:04:53
【问题描述】:
我正在尝试使用 Material UI 样式的组件 API 来注入自定义主题和特定自定义元素的一些道具。
我有一个自定义主题或一些道具可以工作,但不能同时使用
自定义主题
我的自定义主题在单独的文件中定义如下...
export interface ITheme extends Theme {
sidebar: SideBarTheme;
}
type SideBarTheme = {
// Various properties
};
const theme = createMuiTheme(
{
// Normal theme modifications
},
{
sidebar: {
// Custom theme modifications
},
} as ITheme
);
然后我将其与 Material-UI 样式的组件 API 一起使用,如下所示......
const Profile = styled(Button)(({ theme }: { theme: ITheme }) => ({
backgroundColor: theme.sidebar.profile.backgroundColor,
paddingTop: 20,
paddingBottom: 20
}));
这在我的 jsx 中使用 <Profile /> 可以正常工作。
道具
对于道具,我基本上使用的是示例here的精确副本
interface MyButtonProps {
color: string;
}
const Profile = styled( ({ color, ...other }: MyButtonProps & Omit<ButtonProps, keyof MyButtonProps>) => (
<Button {...other} />
))({
backgroundColor: (props: MyButtonProps) => props.color,
paddingTop: 20,
paddingBottom: 20
});
当使用<Profile color="red"/>时,这在我的 jsx 中运行良好
如何让这两者与 typescript 一起工作?
我确实尝试像下面这样组合它们,但道具没有传递...
const Profile = styled( ({ color, ...other }: MyButtonProps & Omit<ButtonProps, keyof MyButtonProps>) => (
<Button {...other} />
))(({ theme }: { theme: ITheme }) => ({
backgroundColor: (props: MyButtonProps) => props.color,
color: theme.sidebar.profile.backgroundColor,
paddingTop: 20,
paddingBottom: 20
}));
我尝试的任何其他方法都会让 TypeScript 感到不安。 material-ui styled 函数也太复杂了,我看不懂。
非常感谢,
【问题讨论】:
标签: reactjs typescript material-ui