【发布时间】:2019-03-13 06:33:31
【问题描述】:
我想用 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
`;
【问题讨论】:
-
如果您能更具体一点会有所帮助 - 您面临的具体问题是什么?您可以提供的信息越多(最好也显示您的代码),更多的人将能够提供帮助:)
-
@JoeClay 谢谢添加更多信息。
-
请将您的导入添加到问题中。我猜
import styledComponents from "styled-components"和import { Button as AntButton } from "antd"但我猜不出IButtonProps来自哪里。 -
@MattMcCutchen 添加了导入。谢谢!
-
刚试过:
export const Button = styledComponents<IButtonProps, any>(AntButton)好像还可以,就是不知道styledComponents<IButtonProps, any>的第二个类型参数是什么意思。
标签: typescript antd styled-components