首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用typescript和emotion在Box组件上修复“属性类型”、“颜色不兼容”

如何使用typescript和emotion在Box组件上修复“属性类型”、“颜色不兼容”
EN

Stack Overflow用户
提问于 2020-08-28 23:27:38
回答 1查看 1K关注 0票数 1

我正在尝试在一个新项目上创建一个通用的Box react组件。这将是所有其他组件的基础。我使用样式系统,情感,最终主题ui来处理我所有组件的主题化和样式。

我的根Box组件如下所示:

代码语言:javascript
复制
import styled from '@emotion/styled';
import {
  compose,
  space,
  layout,
  flexbox,
  border,
  position,
  color,
  SpaceProps,
  ColorProps,
  LayoutProps,
  FlexboxProps,
  BorderProps,
  PositionProps,
} from 'styled-system';

export type BoxProps = SpaceProps &
  ColorProps &
  LayoutProps &
  FlexboxProps &
  BorderProps &
  PositionProps;

export const Box = styled.div<BoxProps>(
  {
    boxSizing: 'border-box',
    minWidth: 0,
  },
  compose(space, color, layout, flexbox, border, position)
);

我使用styled-system中的样式化函数及其相关类型来创建一个Box组件,该组件接受空间、颜色、布局、flexbox、边框和位置属性。

我得到的错误只发生在color属性上。一旦我删除了它,我就不会得到任何错误。

TS错误是:

代码语言:javascript
复制
Type 'BoxProps' does not satisfy the constraint 'Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "color">, "color">'.
  Types of property 'color' are incompatible.
    Type 'string | number | symbol | (string | number | symbol | null)[] | { [x: string]: string | number | symbol | undefined; [x: number]: string | number | symbol | undefined; } | null | undefined' is not assignable to type 'string | undefined'.
      Type 'null' is not assignable to type 'string | undefined'.ts(2344)

这似乎只是一个从样式组件转移到情感的问题,所以我不确定我是否遗漏了一些东西来正确利用情感的类型?

EN

回答 1

Stack Overflow用户

发布于 2021-01-03 04:49:59

如果类型"type“和"as”有错误,则应该在将这些类型插入到已设置样式的组件中之前重新定义这些类型。也许,如果你尝试重写你的道具,它会有所帮助。我的例子:

代码语言:javascript
复制
/* Button component */
const Button: React.FC<ButtonProps> = ({
  isLoading,
  children,
  // should redefine this types, because React.HTMLProps<HTMLButtonElement> has incompatible similar types
  type = 'button',
  as = undefined,
  ...props
}: ButtonProps, ...others) => {
  return (
    <StyledButton {...props} {...others}>
      {isLoading ? 'Loading...' : children}
    </StyledButton>
  );
};

export default Button;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63636738

复制
相关文章

相似问题

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