风格错误解释
@Mosh Feu 的评论为我指明了正确的方向。
您可以添加样式到已经设置样式的组件 https://styled-components.com/docs/basics#extending-styles你可以添加样式到自定义组件 https://styled-components.com/docs/basics#styling-any-component,但是这两件事的工作方式不同。你有一条贯穿这两种类型的链条,所以东西会丢失。
你打电话时withColors(Node)
这是在做什么传递一个生成的className
支撑Node
。但是你的自定义组件Node
永远不会对此道具执行任何操作,因此永远不会应用该样式。
styled 方法可以在您自己的所有组件或任何第三方组件上完美运行,只要它们将传递的 className 属性附加到 DOM 元素即可。
修复样式错误
如果我们编辑Node
使用这个className
,我们得到了颜色!
export const Node: React.FC<IProps & {className?: string}> = ({ id, left, top, className}) => {
return (
<Container left={left} top={top} className={className}>
{id}
</Container>
);
};
TS 错误解释
就打字稿错误而言,您会收到有关分配道具的错误T
到样式组件的 props (ComponentWithAddedColors
),这显示为一堆疯狂的废话:
(道具:(Pick >)|(PropsWithRef &{}),排除<...> | ... 1个以上... |排除<...>> & 部分<...>, 排除<...> | ... 1 个以上... | 排除<...>> & { ...; } & { ... ; }) | (Pick<...> & ... 2 个以上 ... & { ...; })): ReactElement<...>
这主要是因为通过ForwardRefExoticComponent
type.
但是我们可以向后工作,使用实用程序类型从组件类型中获取预期的 props 类型:
type PropsOf<T> = T extends React.ComponentType<infer P> ? P : never;
So ComponentWithAddedColors
有道具PropsOf<typeof ComponentWithAddedColors>
。我们可以使用它,但我们也知道ComponentWithAddedColors
有类型StyledComponent<React.ComponentType<T>, any, {}, never>
,所以我们可以进一步回溯:
type StyledProps<InitialProps> = PropsOf<StyledComponent<React.ComponentType<InitialProps>, any, {}, never>>
So ComponentWithAddedColors
有道具StyledProps<T>
.
已修复 TS 错误
也就是说,这一切都是不必要的,至少在您展示的示例中是这样。你正在传递所有的道具ComponentWithAddedColors
通过到ComponentWithAddedColors
, so result
与组件本身是一样的。直接退货就可以了。
function withColors<T>(Component: React.ComponentType<T>) {
const bg = "hotpink";
return styled(Component)`
${bg && `background: ${bg};`}
`;
}