typescript - 如何用 Styled Components 和 TypeScript 包装 Ant Design?

标签 typescript antd styled-components

我想用 styled-components 包装我的 ant-design 组件,我知道这是可能的 ( https://gist.github.com/samuelcastro/0ff7db4fd54ce2b80cd1c34a85b40c08 ) 但是我在用 TypeScript 做同样的事情时遇到了麻烦。

这是我目前所拥有的:

import { Button as AntButton } from 'antd';
import { ButtonProps } from 'antd/lib/button/button';
import styledComponents from 'styled-components';

interface IButtonProps extends ButtonProps {
   customProp: string;
}

export const Button = styledComponents<IButtonProps>(AntButton)`
  // any custom style here
`;

如您所见,我将我的 ant-design 按钮定义为 as any 以使其工作,否则我会得到一些不兼容的类型,例如:

Argument of type 'typeof Button' is not assignable to parameter of
type 'ComponentType<IButtonProps>'.

Type 'typeof Button' is not assignable to type
'StatelessComponent<IButtonProps>'.

Types of property 'propTypes' are incompatible.

 Property 'customProp' is missing in type '{ 
    type: Requireable<string>; 
    shape: Requireable<string>; 
    size: Requireable<string>; 
    htmlType: Requireable<string>; 
    onClick: ...
    etc
 }

谢谢。

解决方案:

import { Button as AntButton } from 'antd';
import { NativeButtonProps } from 'antd/lib/button/button';
import * as React from 'react';
import styledComponents from 'styled-components';

export const Button = styledComponents<NativeButtonProps>(props => <AntButton {...props} />)`
    // custom-props
`;

最佳答案

我发现了这个古老的问题并尝试以一种简单的方式解决:

import React from 'react';
import styled from 'styled-components';
import { Card } from 'antd';
import { CardProps } from 'antd/lib/card';

export const NewCard: React.FunctionComponent<CardProps> = styled(Card)`
  margin-bottom: 24px;
`;

没有渲染 Prop :D

如果你只需要将一个组件包装成功能组件,那没问题。但是您将失去类组件的属性,例如 Card.Meta

有一个解决方法:

import React from 'react';
import styled from 'styled-components';
import { Card } from 'antd';
import { CardProps } from 'antd/lib/card';

export const NewCard: typeof Card = styled(Card)<CardProps>`
  margin-bottom: 24px;
` as any;

一切(也许……XD)都像原始的 Antd 组件一样工作;)

关于typescript - 如何用 Styled Components 和 TypeScript 包装 Ant Design?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52704785/

相关文章:

javascript - 如何在文本框/文本区域/文本输入中显示自动完成

reactjs - ant design 递归嵌套表不起作用

javascript - 是否可以在发送之前操作 Ant Design Range Picker 数据?

css - styled-components:主题中的样式覆盖组件样式

node.js - Angular6同步加载路线数据

javascript - Angular 三态拨动开关

json - 从 Typescript 解析 JSON 恢复数据成员但不是类型 : cannot call methods on result

javascript - 根据状态和索引动态更改样式组件

reactjs - 在 Material UI 中使用样式组件应用单选按钮颜色?

typescript - 阻止某些文件导入到 VS Code 中