繁体   English   中英

使用Material-UI组件的styled-components typescript错误

[英]styled-components typescript error with Material-UI component

使用typescript并希望为带有样式组件的Material UI组件设置样式。
但是StyledComponent显示Type '{ children: string; }' is missing the following properties 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?

我也在使用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>
)

这几个月前工作正常,但我刚开始一个新项目,我遇到了同样的问题。 必须是更新版本的问题。

可怕,我知道,但与此同时最好:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM