ريأكت جي إس - خطأ في تايبسكريبت مع المكون Material-UI باستخدام styled-components


استخدام TypeScript وأريد تعيين تنسيق لمكوّن Material UI باستخدام styled-components.
لكن يحدث خطأ في النوع مع StyledComponent يظهر النوع '{ children: string; }' يفتقد الخصائص التالية

import React, { PureComponent } from 'react';
import styled from 'styled-components'; // ^4.1.3
import { Button } from '@material-ui/core'; // ^3.9.1

class TestForm extends PureComponent {
  render() {
    return (
      <>
        <Button style={{ backgroundColor: 'red' }}>Work</Button>{/* OK  */}

        <StyledButton>Doesn't work</StyledButton>{/* Type Error happens here <=============== */}
        {/**
          Type '{ children: string; }' is missing the following properties from type 'Pick<Pick<(ButtonProps & RefAttributes<Component<ButtonProps, any, any>>) | (ButtonProps & { children?: ReactNode; }), "form" | "style" | "title" | "disabled" | "mini" | ... 279 more ... | "variant"> & Partial<...>, "form" | ... 283 more ... | "variant">': style, classes, className, innerRef [2739]
         */}
      </>
    );
  }
}

const StyledButton = styled(Button)`
  background: blue;
`;

export default TestForm;

يظهر أن الخاصية children مفقودة.
لقد جربت ما يلي أيضًا ولكن لا يزال لا يعمل.

const StyledButton = styled(Button)<{ children: string; }>`
  background: blue;
`;

هل يعرف أي شخص كيفية استخدام Material UI مع styled-components في TypeScript؟

الإجابة رقم 1

أنا أيضًا أحصل على هذا الخطأ مع material-ui v3.9.3 وstyled-components v4.2.0، وهو أحدث إصدارين في وقت نشر هذا الجواب.

الحل المؤقت لدي لهذا هو التالي

import styled from 'styled-components'
import Button, { ButtonProps } from '@material-ui/core/Button'

const StyledButton = styled(Button)`
  background: blue;
` as React.ComponentType<ButtonProps>

هذا يقوم بتحويل StyledButton إلى نفس نوع Button في واجهة Material UI. إنه يزيل الخطأ ويمنحك نفس التحقق من النوع الذي تحصل عليه مع Button. في معظم الحالات، هذا كل ما تحتاجه.

في الحالات التي تحتاج فيها إلى خصائص إضافية لاستخدامها في الأنماط، وترغب في التأكد من أنها مرسلة، يمكنك ببساطة توسيع ButtonProps والتحويل إلى هذا النوع المخصص:

type StyledButtonProps = ButtonProps & { background: string }

const StyledButton = styled(Button)`
  background: ${(props: StyledButtonProps) => props.background};
` as React.ComponentType<StyledButtonProps>


const MyComponent = () => (
  <div>
    <StyledButton size='small' background='blue'>one</StyledButton>

    // ERROR HERE - forgot the 'background' prop
    <StyledButton size='small'>two</StyledButton>
  </div>
)