首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Omit<Typography,'color'>不能正常工作

Omit<Typography,'color'>不能正常工作
EN

Stack Overflow用户
提问于 2021-08-30 19:11:54
回答 2查看 92关注 0票数 2

所以这个示例代码如下:

代码语言:javascript
复制
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}
`;

并不像你所期望的那样工作。这里的想法是:colorPaletteProps中是any类型的,但在TypographyProps中是"inherit" | "primary" | "secondary" | "textPrimary" | ... | undefined类型的。我想做的是覆盖颜色属性,这样我就可以使用@material-ui/systemcolor,而不是Typographycolor属性。

也许我做错了什么,或者可能有什么我没有考虑到。下面是一个CodeSandbox网址,其中包含正在复制的错误:

https://codesandbox.io/s/b36zs?file=/src/App.tsx (将<Text ...>组件悬停在Typescript错误上-它不会阻止编译,但在本地根本不起作用)。

这里我漏掉了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-09-15 21:13:53

根据您的回答(AndréCastelo),您可以通过创建原始材料UI组件和类型的别名来改进这段代码,因为组件TypographyWithoutColor由于使用了PaletteProps的颜色属性而令人困惑。此外,您的覆盖将更加清晰,因为您不需要为需要覆盖或增强的组件或类型创建新名称。

所以它看起来是这样的:

代码语言:javascript
复制
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}
`;
票数 3
EN

Stack Overflow用户

发布于 2021-08-30 19:39:27

所以Emile的评论给了我一个想法,我把代码改成

代码语言:javascript
复制
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}
`;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68989227

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档