首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Material-UI组件的styled-components typescript错误

Material-UI组件的styled-components typescript错误
EN

Stack Overflow用户
提问于 2019-02-04 11:33:58
回答 2查看 4.7K关注 0票数 8

使用typescript并希望使用样式化组件为Material UI组件设置样式。

但是显示Type '{ children: string; }' is missing the following properties的StyledComponent会出现类型错误

代码语言:javascript
复制
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;

它显示儿童道具丢失。

我也尝试了以下方法,但仍然不起作用。

代码语言:javascript
复制
const StyledButton = styled(Button)<{ children: string; }>`
  background: blue;
`;

有人知道如何在typescript中使用带有样式组件的Material UI吗?

EN

回答 2

Stack Overflow用户

发布于 2019-04-29 23:24:56

我在material-ui v3.9.3styled-components v4.2.0上也遇到了这个错误,这两个版本是发布此答案时的最新版本。

我对此的解决方法如下

代码语言:javascript
复制
import styled from 'styled-components'
import Button, { ButtonProps } from '@material-ui/core/Button'

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

这会将StyledButton强制转换为与材质UI Button相同的类型。它消除了错误,并为您提供了与Button相同的类型检查。在大多数情况下,这就是你想要的。

如果您需要在样式中使用额外的属性,并且希望强制传递这些属性,您只需扩展ButtonProps并将其强制转换为该自定义类型:

代码语言:javascript
复制
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>
)
票数 12
EN

Stack Overflow用户

发布于 2019-02-10 00:49:13

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

很可怕,我知道,但同时最好还是:

代码语言:javascript
复制
const StyledButton: any = styled(Button)`
  background: blue;
`;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54509851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档