reactjs - 使用样式化组件和 Material UI : `React does not recognize the ` showText` prop on a DOM element` 时出现 Typescript 和 eslint 问题

标签 reactjs typescript material-ui eslint styled-components

我正在使用 s 样式组件返回一个 Material 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 个 lint 和 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 Prop 的来源,它在 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)};
});

这样您就可以告诉编译器您的 props 没有用作 DOM props。

关于reactjs - 使用样式化组件和 Material UI : `React does not recognize the ` showText` prop on a DOM element` 时出现 Typescript 和 eslint 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64135464/

相关文章:

javascript - 当我上传文件后尝试读取事件目标时,事件目标返回为空

javascript - 列表未正确加载到reactjs程序中

javascript - 文本节点不能是 <View> 的子节点

typescript - Typescript 中的类型和类有什么区别?

javascript - 使用 Typescript + ngMock 模块

reactjs - 组件样式是否可以限定范围而不是内联以防止在同一页面上被多个 React 应用程序覆盖?

reactjs - 如何自定义 mui 分页栏?

reactjs - Tailwind 类在安装后无法与 React 一起使用

typescript - 如何正确键入对象方法的包装函数?

css - Material 用户界面 : Give TableBody a max height and make it vertically scrollable