HOC中的样式化组件

时间:2019-08-05 09:22:40

标签: reactjs typescript styled-components

我想使用高阶组件将样式添加到组件包装器中。打字稿说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;
}

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

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

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

  return ColoredComponent;
}

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

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

  return ColoredComponent;
}

1 个答案:

答案 0 :(得分: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" />

但是,如果您想锁定颜色而不希望公开颜色道具,那么恐怕您可能已经公开了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' })