我正在使用 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/