所以这个示例代码如下:
import { Typography, TypographyProps } from '@material-ui/core';
import { palette, PaletteProps } from '@material-ui/system';
import styled from '@emotion/styled';
type TextProps = Omit<TypographyProps, 'color'> & PaletteProps;
export const Text = styled(Typography)<TextProps>`
${palette}
`;并不像你所期望的那样工作。这里的想法是:color在PaletteProps中是any类型的,但在TypographyProps中是"inherit" | "primary" | "secondary" | "textPrimary" | ... | undefined类型的。我想做的是覆盖颜色属性,这样我就可以使用@material-ui/system的color,而不是Typography的color属性。
也许我做错了什么,或者可能有什么我没有考虑到。下面是一个CodeSandbox网址,其中包含正在复制的错误:
https://codesandbox.io/s/b36zs?file=/src/App.tsx (将<Text ...>组件悬停在Typescript错误上-它不会阻止编译,但在本地根本不起作用)。
这里我漏掉了什么?
发布于 2021-09-15 21:13:53
根据您的回答(AndréCastelo),您可以通过创建原始材料UI组件和类型的别名来改进这段代码,因为组件TypographyWithoutColor由于使用了PaletteProps的颜色属性而令人困惑。此外,您的覆盖将更加清晰,因为您不需要为需要覆盖或增强的组件或类型创建新名称。
所以它看起来是这样的:
import { Typography as MuiTypography, TypographyProps as MuiTypographyProps } from '@material-ui/core';
import { palette, PaletteProps } from '@material-ui/system';
import styled from '@emotion/styled';
export type TypographyProps = PaletteProps & Omit<MuiTypographyProps, 'color'>;
export const Typography = styled(({ color, ...props }: TypographyProps) => (
<MuiTypography {...props} />
))<TypographyProps>`
${palette}
`;发布于 2021-08-30 19:39:27
所以Emile的评论给了我一个想法,我把代码改成
import { Typography, TypographyProps } from '@material-ui/core';
import { palette, PaletteProps } from '@material-ui/system';
import styled from '@emotion/styled';
type TextProps = Omit<TypographyProps, 'color'> & PaletteProps;
const TypographyWithoutColor = ({ color, ...props }: TextProps) => (
<Typography {...props} />
);
export const Text = styled(TypographyWithoutColor)<TextProps>`
${palette}
`;https://stackoverflow.com/questions/68989227
复制相似问题