antd - 如何使用 Styled Components 和 TypeScript 包裝 Ant Design?
我想用 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
`;如你所見,我正在使用 as any 來定義我的 ant-design 按鈕,以使它正常工作,否則我會得到一些不相容的類型,例如:
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
`;
答案#1
我找到這個古老的問題,並試圖以簡單的方式解答:
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;
`;
沒有 render props :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 元件一樣運作 ;)
答案#2
上述的解決方法對我沒用,但這個解決了問題。
const Button = styled((props: NativeButtonProps) => <AntButton {...props} />)``;
