Как обернуть Ant Design со стилизованными компонентами и TypeScript? - PullRequest
0 голосов
/ 08 октября 2018

Я хочу обернуть свои компоненты 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
`;

Как вы можете видеть, я определяю свою кнопку ant-design с помощью as any, чтобы она работала, в противном случае я получаю несколько несовместимых типов, таких как:

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

Ответы [ 4 ]

0 голосов
/ 30 августа 2019

Я нашел этот древний вопрос и пытаюсь решить его простым способом:

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

0 голосов
/ 29 января 2019

Вышеуказанные решения не сработали для меня, но это помогло.

const Button = styled((props: NativeButtonProps) => <AntButton {...props} />)``;
0 голосов
/ 31 января 2019

index.tsx (Компонент кнопки)

import { Button as AntButton } from 'antd'
import { NativeButtonProps } from 'antd/lib/button/button'
import 'antd/lib/button/style/css'
import * as React from 'react'
import styledComponents from 'styled-components'
import * as colours from '../colours'

const getColour = (props: any) =>
  props.status === 'green'
    ? colours.STATUS_GREEN
    : props.status === 'red'
      ? colours.STATUS_RED
      : props.type === 'primary'
        ? colours.PRIMARY
        : colours.WHITE

export interface ButtonProps extends NativeButtonProps {
  status?: string
}

export default styledComponents((props: ButtonProps) => <AntButton {...props} />)`
  &:focus,
  &:hover
  & {
    background-color: ${getColour};
    border-color: ${getColour};
  }
`
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js"></script>

import React from 'react'
import Button, { ButtonProps } from './index'

interface ButtonAsyncSingleSuccessProps extends ButtonProps {
  clickFunc: any, // (...args: any[]) => Promise<any>
  labelLoading: string,
  labelReady: string,
  labelSuccess: string,
}

interface ButtonAsyncSingleSuccessState {
  label: string,
  loading: boolean,
  status: string
}

export default class ButtonAsyncSingleSuccess extends React.Component<
  ButtonAsyncSingleSuccessProps,
  ButtonAsyncSingleSuccessState
> {
  constructor (props: any) {
    super(props)
    this.state = {
      label: props.labelReady,
      loading: false,
      status: ''
    }
  }
  public clickHandler (event: any) {
    const { labelLoading, labelReady, labelSuccess, clickFunc } = this.props
    this.setState({
      label: labelLoading,
      loading: true,
      status: ''
    })
    clickFunc(event)
      .then(() => {
        this.setState({
          label: labelSuccess,
          loading: false,
          status: 'green'
        })
      })
      .catch(() => {
        this.setState({
          label: labelReady,
          loading: false,
          status: 'red'
        })
      })
  }
  public render () {
    const {
      labelLoading,
      labelReady,
      labelSuccess,
      clickFunc,
      ...props
    } = this.props
    const { label, loading, status } = this.state
    if (status === 'red') {
      setTimeout(() => this.setState({ status: '' }), 1000) // flash red
    }
    return (
      <Button
        {...props}
        loading={loading}
        status={status}
        onClick={(e) => this.clickHandler(e)}
      >
        {label}
      </Button>
    )
  }
}
0 голосов
/ 10 октября 2018

Похоже, корень проблемы в том, что styled-components ожидает, что внутренний компонент (AntButton) примет все реквизиты в указанном интерфейсе (IButtonProps), а AntButton -не принимаю customProp.Чтобы это исправить, следуйте последнему примеру в этом разделе документации и используйте компонент функции без сохранения состояния для удаления customProp перед вызовом AntButton.

export const Button = styledComponents<IButtonProps>(
  ({ customProp, ...rest }) => <AntButton {...rest} />)`
  // any custom style here
`;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...