HOC 中的样式组件

IT技术 reactjs typescript styled-components
2021-05-07 19:54:08

我想使用高阶组件向我的组件包装器添加样式。typescript说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;
}

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

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

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

  return ColoredComponent;
}

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

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

  return ColoredComponent;
}
1个回答

这是你想要做的吗?

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" />

但是,如果您想锁定颜色而不暴露颜色props,那么恐怕您可能已经暴露了 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' })