antd - Hur man paketerar Ant Design med Styled Components och TypeScript?


Jag vill slå in mina ant-design-komponenter med styled-components, jag vet att detta är möjligt (https://gist.github.com/samuelcastro/0ff7db4fd54ce2b80cd1c34a85b40c08) men jag har problem med att göra samma sak med TypeScript.

Detta är vad jag har hittills:

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

Som du kan se definierar jag min ant-design-knapp med as any för att få den att fungera, annars får jag några inkompatibla typer som:

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
 }

Tack.

Lösning:

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

Svar #1

Jag har hittat denna gamla fråga och försöker lösa den på ett enkelt sätt:

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

utan render-props :D

om du bara behöver wrappa en komponent som en funktionskomponent, är det okej. Men du kommer att förlora egenskaperna hos en klasskomponent såsom Card.Meta.

Det finns en lösning:

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;

Allt (kanske... XD) fungerar som originalet Antd-komponent ;)

Svar #2

De ovanstående lösningarna fungerade inte för mig, men detta löste det.

const Button = styled((props: NativeButtonProps) => <AntButton {...props} />)``;

Relaterade artiklar