styled-components typescript error with Material-UI component

主宰稳场 提交于 2019-12-03 14:52:55

I'm also getting this error with material-ui v3.9.3 and styled-components v4.2.0, the latest versions at the time of posting this answer.

My workaround for this is the following

import styled from 'styled-components'
import Button, { ButtonProps } from '@material-ui/core/Button'

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

This casts StyledButton to the same type as the Material UI Button. It removes the error and gives you the same type checking as you get for Button. In most cases this is all you want.

In cases where you need additional props to use in the styles, and want to enforce they are passed, you can just extend ButtonProps and cast to that custom type:

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>
)

This was working fine a few months ago, but I just started a new project and am having the same issue. Must be a problem with the more recent versions.

Horrible, I know, but in the meantime maybe best to:

const StyledButton: any = styled(Button)`
  background: blue;
`;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!