Cor*_*ere 5 emotion typescript styled-components theme-ui styled-system
Box我正在尝试在新项目上制作通用的反应组件。这将是所有其他组件的基础。我使用 styled-system、emotion 以及最终的 theme-ui 来处理所有组件的主题和样式。
我的根Box组件如下所示:
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)
);
Run Code Online (Sandbox Code Playgroud)
我使用 styled-system 中的 styled 函数及其关联类型来创建一个接受空间、颜色、布局、flexbox、边框和位置属性的 Box 组件。
我收到的错误仅发生在color道具上。一旦我删除它,我就不会收到任何错误。
TS 错误为:
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)
Run Code Online (Sandbox Code Playgroud)
这似乎只是从样式组件转向情感时的一个问题,所以我不确定是否缺少一些东西来正确利用情感的类型?
小智 1
如果“type”和“as”类型有错误,您应该在将它们插入样式组件之前重新定义这些类型。也许,如果你尝试重写你的 props,它会有所帮助。我的例子:
/* 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;
Run Code Online (Sandbox Code Playgroud)