Material-UI组件的样式化组件打字稿错误 [英] styled-components typescript error with Material-UI component
问题描述
使用打字稿,并要为具有样式组件的Material UI组件设置样式.
但是StyledComponent显示Type '{ children: string; }' is missing the following properties
Using typescript and want to set styling for Material UI component with styled-components.
But type error happens with StyledComponent showing 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;
这表明缺少儿童道具.
我也尝试了以下方法,但仍然无法正常工作.
It is showing children prop is missing.
I have tried the following too but still doesn't work.
const StyledButton = styled(Button)<{ children: string; }>`
background: blue;
`;
有人知道如何将Material UI与打字稿中的样式组件一起使用吗?
Does anyone know how to use Material UI with styled-components in typescript?
推荐答案
我也在material-ui
v3.9.3 和styled-components
v4.2.0 strong>,发布此答案时的最新版本.
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.
以下是我的解决方法
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
相同的类型检查.在大多数情况下,这就是您想要的.
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.
如果需要在样式中使用其他道具并想要强制传递它们,则可以扩展ButtonProps
并强制转换为该自定义类型:
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>
)
这篇关于Material-UI组件的样式化组件打字稿错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!