HOC 中的样式组件 [英] Styled component in HOC

查看:23
本文介绍了HOC 中的样式组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add styles to my component wrapper using higher order component. Typescript says there is error with 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 的组件时,也会出现类型检查错误.

When I want to return Component that was passed to HOC with {...componentProps} there is also typecheck error.

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

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

  return ColoredComponent;
}

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

But, when I pass everything to Component with {...props} there is not typecheck error.

...
{
  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);然而,我确实以不同的方式处理它.

If you wanted to lock-in your colors and not expose the color props, however, then I'm afraid you might have exposed a TypeScript bug. I can't seem to get around it myself (without using additionalProps as any); however, I did approach it a bit differently.

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' })

这篇关于HOC 中的样式组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆