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

时间:2019-02-04 03:33:58

标签: reactjs typescript 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;

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

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

有人知道如何将Material UI与打字稿中的样式组件一起使用吗?

2 个答案:

答案 0 :(得分:2)

我也收到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转换为与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>
)

答案 1 :(得分:0)

这在几个月前还不错,但是我刚刚开始一个新项目,并且遇到了同样的问题。一定是最新版本存在问题。

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

const StyledButton: any = styled(Button)`
  background: blue;
`;
相关问题