使用样式化组件和Material UI时出现打字稿和夹板问题:“ React无法识别DOM元素上的showText道具”

问题描述

我正在使用s样式的组件返回物料ui Fab组件,并且在控制台中出现以下错误

React does not recognize the `showtext` prop on a DOM element.
  If you intentionally want it to appear in the DOM as a custom attribute,spell it as lowercase `showtext` instead

以下是组件:

import styled from 'styled-components';
import MuiFab from '@material-ui/core/Fab';

type TFabContainer = {
    showtext: boolean;
}
const FabContainer = styled(MuiFab)<TFabContainer>`
    width: 250px;
    animation-duration: ${({ showtext }) => (showtext ? '0.25s' : '1s')};
    animation-iteration-count: linear;
    animation-name: ${({ showtext }) => (showtext ? expand : contract)};
`;

我知道为什么会发生此警告,所以我设法将其更改为

import styled from 'styled-components';
import MuiFab,{ FabProps } from '@material-ui/core/Fab';

type TFabContainer = {
    showtext: boolean;
    rest: FabProps;
}
const FabContainer = styled(({ showtext,...rest }: TFabContainer) => <MuiFab {...rest} />)`
    width: 250px;
    animation-duration: ${({ showtext }) => (showtext ? '0.25s' : '1s')};
    animation-iteration-count: linear;
    animation-name: ${({ showtext }) => (showtext ? expand : contract)};
`;

这可以消除错误,并以预期的行为正确呈现我的组件,但是现在我收到了2条皮棉和TS警告:

const FabContainer = styled(({ showtext,...rest }: TFabContainer) => <MuiFab {...rest} />)`
                               ^^^^^^^^                                ^^^^^^
'showtext' is defined but never used ↑                                  ↑ Property 'href' is missing in type '{ rest: OverrideProps<FabTypeMap<{},"button">,"button">; }' but required in type '{ href: string; }'.

这些错误以前不在这里。不确定href道具来自何处,MuiFab不需要。

解决方法

有点肿,但实际上是推荐的方式:

const FabContainer = styled(({ showText,...rest }: TFabContainer & Omit<MuiFabProps,keyof TFabContainer>)) => <MuiFab {...rest} />)({
    width: 250px;
    animation-duration: ${({ showText }) => (showText ? '0.25s' : '1s')};
    animation-iteration-count: linear;
    animation-name: ${({ showText }) => (showText ? expand : contract)};
});

通过这种方式,您告诉编译器您的道具没有用作DOM道具。