HOC 中的样式化组件

Styled component in HOC

我想使用高阶组件向我的组件包装器添加样式。打字稿说 ComponentWithAdddedColors.

有错误
type Props = {
  bg?: string;
};

function withColors<TProps>(
  Component: React.ComponentType<TProps>
): React.ComponentType<TProps & Props> {

  const ColoredComponent: React.ComponentType<TProps & Props> = props => {
    const { bg, ...componentProps } = props;

    const ComponentWithAdddedColors = styled(Component)`
      ${bg && `background: ${bg};`}
    `;

    return <ComponentWithAdddedColors {...componentProps} />; //Typecheck error
  };

  return ColoredComponent;
}

当我想要 return 传递给 HOC 的组件 {...componentProps} 时,也会出现类型检查错误。

...
{
  const ColoredComponent: React.ComponentType<TProps & Props> = props => {
    const { bg, ...componentProps } = props;

    return <Component {...componentProps} />; //Typecheck error
  };

  return ColoredComponent;
}

但是,当我使用 {...props} 将所有内容传递给组件时,没有类型检查错误。

...
{
  const ColoredComponent: React.ComponentType<TProps & Props> = props => {
    return <Component {...props} />; //No error
  };

  return ColoredComponent;
}

这是你想要做的吗?

export function withColors<T>(Component: React.ComponentType<T>) {
    return styled(Component)<Props>`
        ${({ bg }) => bg && `background: ${bg};`}
    `
}

const Foo: React.FC<{ bar: string }> = props => <div>{props.bar}</div>
const ColoredFoo = withColors(Foo)
export const redFoo = <ColoredFoo bg="red" bar="baz" />

但是,如果您想锁定颜色而不暴露颜色道具,恐怕您可能已经暴露了 TypeScript 错误。我自己似乎无法绕过它(不使用 additionalProps as any);但是,我确实采用了一些不同的方法。

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

export const RedFoo = withColors(Foo, { bg: 'red' })