【问题标题】:MUI styled component + a new prop (Typescript)MUI 风格的组件 + 一个新的道具(Typescript)
【发布时间】:2020-11-18 04:17:18
【问题描述】:

我有 ListItem,我希望您在某些情况下将其设为红色。我创建了样式化的 mui 组件:

function StyledListItem({ hasErrors, ...props }) {
  const classes = listItemStyles();
  return (
    <ListItem
      classes={{
        root: clsx({
          [classes.root]: hasErrors,
        }),
        selected: clsx({
          [classes.selected]: hasErrors,
        }),
      }}
      {...props}
    />
  );
}

在这种情况下,我遇到了 ESLint 错误:“道具验证中缺少'hasErrors'”。如果我这样做

function StyledListItem(props: any) {
...
}

我收到警告:React 无法识别 DOM 元素上的 hasErrors 属性。如果您有意希望它作为自定义属性出现在 DOM 中,请将其拼写为小写 haserrors。如果您不小心从父组件传递了它,请将其从 DOM 元素中移除。

如何摆脱“道具验证中缺少'hasErrors'”错误?

【问题讨论】:

  • 你能把它放在一个沙箱里,这样你就可以看到你的实现了吗?你的实施是第一个还是第二个?由于第一个从 props 中删除了 hasErrors。
  • codesandbox.io/s/… 由于没有 ESlint,代码框上没有错误,但正如我所说,它不喜欢函数 StyledListItem({ hasErrors, ...props }) 它说缺少“hasErrors”在道具验证中

标签: reactjs material-ui


【解决方案1】:

你需要像这样将 ts 类型添加到 props 中:

function StyledListItem({ hasErrors, ...props }: {hasErrors: boolean}) {

这将告诉 typescript 至少有 hasError 属性。 这会让你像你一样提取它。

你应该阅读更多关于 react + typescript 的内容。 如果需要孩子,可以使用 React.FC 类型:

function StyledListItem({ hasErrors, ...props }: {hasErrors: boolean, children: JSX.Element}) {

【讨论】:

  • 我试过了,在这种情况下我得到 Type '{ children: Element[];按钮:真; hasErrors:布尔值;选择:布尔值; onClick: () => 无效; }' 不可分配给类型 'IntrinsicAttributes & { hasErrors: boolean; }'。 'IntrinsicAttributes & { hasErrors: boolean; 类型上不存在属性 'children' }'。
  • 还需要提一下,那个函数不是一个组件,只是和主文件在同一个文件中的一个函数。
  • 我更新了我的回答,你是什么意思它不是一个组件?你要返回什么?
  • 得到同样的错误,它要求提供所有的道具,如按钮、选定、onClick 等。说 StyledListItem 不是一个组件,我的意思是它只是一个函数。喜欢这里codesandbox.io/s/…
【解决方案2】:

在界面中添加[key: string]: React.ReactNode;解决了这个问题。

interface IStyledListItemProps {
  hasErrors: boolean;
  [key: string]: React.ReactNode;
}

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2022-08-21
    • 2021-05-28
    • 2018-11-25
    • 2022-07-19
    • 2022-06-11
    • 1970-01-01
    • 2022-12-22
    • 2022-11-11
    相关资源
    最近更新 更多