【问题标题】:styled-components typescript error with Material-UI componentMaterial-UI 组件的 styled-components 打字稿错误
【发布时间】:2019-06-27 19:44:08
【问题描述】:

使用 typescript 并希望使用 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;
`;

有人知道如何在 typescript 中使用 Material UI 和 styled-components 吗?

【问题讨论】:

    标签: reactjs typescript material-ui styled-components


    【解决方案1】:

    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>
    

    这会将 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>
    )
    

    【讨论】:

    【解决方案2】:

    几个月前它运行良好,但我刚刚开始了一个新项目并且遇到了同样的问题。一定是较新的版本有问题。

    很糟糕,我知道,但与此同时,最好的办法是:

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

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 2018-06-23
      • 2019-10-17
      • 2020-08-12
      • 2021-05-19
      • 2020-03-28
      • 2019-08-02
      • 2020-05-12
      • 2020-11-16
      相关资源
      最近更新 更多