使用typescript并希望使用样式化组件为Material UI组件设置样式。
但是显示Type '{ children: string; }' is missing the following properties的StyledComponent会出现类型错误
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吗?
发布于 2019-04-29 23:24:56
我在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强制转换为与材质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>
)发布于 2019-02-10 00:49:13
这在几个月前工作得很好,但我刚刚开始了一个新项目,并且遇到了同样的问题。一定是较新版本的问题。
很可怕,我知道,但同时最好还是:
const StyledButton: any = styled(Button)`
background: blue;
`;https://stackoverflow.com/questions/54509851
复制相似问题