【问题标题】:React Typescript prop error in ListItem (Material UI component)ListItem(Material UI组件)中的React Typescript prop错误
【发布时间】:2026-01-19 11:30:02
【问题描述】:

我对 ContainerComponent 和 ContainerProps 有疑问,我认为问题在于“li”是字符串类型,我需要明确将其定义为 React.ElementType,但我不知道怎么做。

<ListItem
  ContainerComponent="li"
  ContainerProps={{ ref: provided.innerRef }}
  {...provided.draggableProps}
  {...provided.dragHandleProps}
  style={getItemStyle(
      snapshot.isDragging,    
      provided.draggableProps.style
  )}
>

我得到的错误:

没有重载匹配这个调用。 最后一个重载给出了以下错误。 类型 '"li"' 不可分配给类型 'ElementType |不明确的'。 类型 '{ ref: (element?: HTMLElement | null | undefined) => any; }' 不可分配给类型 'HTMLAttributes'。 对象字面量只能指定已知属性,而 'ref' 不存在于类型 'HTMLAttributes'.ts(2769)

【问题讨论】:

  • 我对组件不熟悉,但如果它想要 ElemenType,请尝试给它 type - ContainerComponent={(&lt;li/&gt;).type}
  • "我认为问题在于 "li" 是字符串类型" 不是这样。它被推断为字符串文字,这很好。 React.ElementType&lt;React.HTMLAttributes&lt;HTMLDivElement&gt;&gt; 类型解析为大约 70 个字符串文字元素名称的联合。我猜"li" 不是其中之一吗?我看不到整个列表。
  • Type '"li"' is not assignable to type '"object" | "abbr" | "address" | "article" | "aside" | "b" | "bdi" | "bdo" | "big" | "blockquote" | "caption" | "cite" | "code" | "col" | "colgroup" | "dd" | "del" | "details" | "dfn" | ... 61 more ... | undefined'
  • @LindaPaiste 不确定发生了什么,但'li'ContainerComponent 如果not provided 的默认值
  • 完美,感谢分享!

标签: reactjs typescript types material-ui react-props


【解决方案1】:

通过写作解决了这个问题:

<ListItem
ContainerComponent={(<li />).type}
ref={provided.innerRef}                                             
{...provided.draggableProps}                                                 
{...provided.dragHandleProps}
style={getItemStyle                                                      
snapshot.isDragging,                                                      
provided.draggableProps.style)}

【讨论】:

    最近更新 更多