如何用 Styled Components 和 TypeScript 来结束 Ant Design? [英] How to wrap up Ant Design with Styled Components and TypeScript?
问题描述
我想用样式化组件包装我的 ant-design 组件,我知道这是可能的 (https://gist.github.com/samuelcastro/0ff7db4fd54ce2b80cd1c34a85b40c08)但是我在使用 TypeScript 时遇到了麻烦.
I want to wrap up my ant-design components with styled-components, I know that this is possible (https://gist.github.com/samuelcastro/0ff7db4fd54ce2b80cd1c34a85b40c08) however I'm having troubles to do the same with 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
`;
如您所见,我正在使用 as any
定义我的 ant-design 按钮以使其工作,否则我会得到一些不兼容的类型,例如:
As you can see I'm defining my ant-design button with as any
in order to make it work, otherwise I get some incompatible types like:
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
`;
推荐答案
我发现了这个古老的问题,并试图以一种简单的方式解决:
I have found this ancient question and try to solve in an easy way:
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;
`;
没有渲染道具:D
如果你只是需要把一个组件包装成函数组件,那也行.但是你会丢失类组件的属性,比如Card.Meta
.
if you just need wrap a component as function component, that's all right. But you will lose the properties of class component such as 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 组件一样工作;)
Everything (maybe... XD) works as original Antd Component ;)
这篇关于如何用 Styled Components 和 TypeScript 来结束 Ant Design?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!