Material-UI组件的样式化组件打字稿错误

Thu*_*San 6 typescript reactjs material-ui styled-components

使用打字稿,并希望为具有样式组件的Material UI组件设置样式。
但是StyledComponent显示时发生类型错误Type '{ children: string; }' is missing the following properties

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;
Run Code Online (Sandbox Code Playgroud)

它表明儿童道具丢失。
我也尝试了以下方法,但仍然无法正常工作。

const StyledButton = styled(Button)<{ children: string; }>`
  background: blue;
`;
Run Code Online (Sandbox Code Playgroud)

有谁知道如何将Material UI与Typescript中的样式组件一起使用?

dav*_*wil 5

发布此答案时,最新版本material-ui v3.9.3styled-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>
Run Code Online (Sandbox Code Playgroud)

转换StyledButton为与Material UI相同的类型Button。它消除了错误,并为您提供与类型相同的类型检查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>
)
Run Code Online (Sandbox Code Playgroud)


小智 0

几个月前,这工作得很好,但我刚刚开始一个新项目,遇到了同样的问题。应该是最新版本的问题。

我知道这很可怕,但与此同时也许最好:

const StyledButton: any = styled(Button)`
  background: blue;
`;
Run Code Online (Sandbox Code Playgroud)