作者:手机用户2502917943 | 来源:互联网 | 2022-11-18 20:59
使用打字稿,并希望为具有样式组件的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 (
<>
{/* OK */}
{/* Type Error happens here <=============== */}
{/**
Type '{ children: string; }' is missing the following properties from type 'Pick>) | (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与Typescript中的样式组件一起使用?
1> davnicwil..:
发布此答案时,最新版本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
转换StyledButton
为与Material UI相同的类型Button
。它消除了错误,并为您提供与类型相同的类型检查Button
。在大多数情况下,这就是您想要的。
如果您需要在样式中使用其他道具并想要强制传递它们,则可以扩展ButtonProps
并强制转换为该自定义类型:
type StyledButtOnProps= ButtonProps & { background: string }
const StyledButton = styled(Button)`
background: ${(props: StyledButtonProps) => props.background};
` as React.ComponentType
// ERROR HERE - forgot the 'background' prop