如何用样式化组件和TypeScript来包装Ant Design? [英] How to wrap up Ant Design with Styled Components and TypeScript?

查看:208
本文介绍了如何用样式化组件和TypeScript来包装Ant Design?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用样式化的组件包装我的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.

这是我到目前为止所拥有的:

This is what I have so far:

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 ;)

这篇关于如何用样式化组件和TypeScript来包装Ant Design?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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