簡體   English   中英

React TypeScript 和 ForwardRef - 類型“IntrinsicAttributes”上不存在屬性“ref”

[英]React TypeScript & ForwardRef - Property 'ref' does not exist on type 'IntrinsicAttributes

在與 React 和 TypeScript 中的類型和 forwardRefs 斗爭了一段時間之后,我希望其他人可以為我解決這個問題。

我正在構建一個 DataList 組件,它由三部分組成:

  • 容納所有事件偵聽器和邏輯的容器
  • 列出自身,一個ul
  • 列表項,一個li

最終,用法將如下所示:

<DataList.List ...>
  <DataList.Item ...>content</DataList.Item>
</DataList.List>

為了實現我需要的功能,我使用了 React.forwardRef,但發現 TypeScript 很難做到這一點,因為我很難正確鍵入組件以接收ref以及children項和其他道具。

數據列表容器
我本質上希望這個組件只處理邏輯和事件偵聽器,同時返回主要的 DataList 組件(如下所示)。 但這里的關鍵是我需要在這里創建 DataList ref 並將其分配給返回的組件。

const DataListContainer: React.FC = ({ children }) => {
  const listRef = useRef<HTMLUListElement>(null);

  return (
      <DataList ref={listRef}>{children}</DataList>
  );
};

數據列表
我希望 DataList 組件只處理它的 UI 和道具。

interface Props extends TestId {
  focusedItemId?: string;
}

const DataList: React.FC<Props> = React.forwardRef<HTMLUListElement, Props>(
  ({ children, focusedItemId, testId }, ref) => {
    return (
      <ul
        aria-activedescendant={focusedItemId}
        data-test-id={testId}
        ref={ref}
      >
        {children}
      </ul>
    );
  },
);

不過,這並不完全正確。 因為這個設置給了我錯誤

Type '{ children: any[]; ref: RefObject<HTMLUListElement>; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.
  Property 'ref' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.

你快到了! React TypeScript Cheatsheet之后,問題出在DataList道具上。 添加兒童道具將解決它

interface Props extends TestId {
  children?: ReactNode;
  focusedItemId?: string;
}

我在這個 CodeSandbox中重新創建了一個簡單的示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM