我想用 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/