临时反应组件中的样式组件

2024-01-07

我在反应中的临时包装器中使用样式组件时遇到两个问题。

  1. 组件已渲染,但不使用背景颜色。
  2. ComponentWithAddedColors 不是有效的打字稿。不知道为什么。

有谁可以帮忙解决这个问题吗?

interface IProps {
  id: string;
  left: number;
  top: number;
}

export const Node: React.FC<IProps> = ({ id, left, top }) => {
  return (
    <Container left={left} top={top}>
      {id}
    </Container>
  );
};

function withColors<T>(Component: React.ComponentType<T>) {
  const bg = "hotpink";
  const ComponentWithAddedColors = styled(Component)`
    ${bg && `background: ${bg};`}
  `;
  const result: React.FC<T> = (props) => (
    <ComponentWithAddedColors {...props} />
  );
  return result;
}

const DraggableNode = withColors(Node);
export default DraggableNode;

我做了一个代码沙箱来说明这个问题:https://codesandbox.io/s/styled-hoc-xgduo?file=/src/Components/Node/Node.tsx https://codesandbox.io/s/styled-hoc-xgduo?file=/src/Components/Node/Node.tsx


风格错误解释

@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};`}
  `;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

临时反应组件中的样式组件 的相关文章

随机推荐