簡體   English   中英

為帶有特定 props 的 React 組件輸入類型

[英]Type for a React component with certain props

我想表達采用某些道具的組件的類型:

舉個例子,我想渲染任何接受ISINrate的東西:

type Props = {
  Item: TheQuestion;
  data: {ISIN: string, ...};
}
function Renderer({Item, data}: Props) {
  return <foo>
    <bar />
    <Item ISIN={data.ISIN} rate={80/64} />
  </foo>;
}

我怎么能在這里寫出我稱之為TheQuestion的類型?

一種有效的方法是React.FunctionComponent<{ISIN: string, rate: number}> ,但這僅允許function組件,而不是基於class的組件。

是否有一種通用類型可以同時滿足兩者?

是的, React.ComponentType 這是它的類型定義。 它需要一個通用類型參數作為道具。

type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;

對於您的用例,這就是實現的樣子,

import React, { FC, ComponentType } from 'react';

type Props = {
  Item: ComponentType<{ ISIN: string; rate: number }>;
  data: { ISIN: string, /* other types... */ };
};

function Renderer({ Item, data }: Props) {
  return (
    <Foo>
      <Bar />
      <Item ISIN={data.ISIN} rate={80 / 64} />
    </Foo>
  );
}

const Foo: FC = ({ children }) => {
  return <div>{children}</div>;
};

const Bar: FC = () => {
  return <div>Hello</div>;
};

PS-我建議將傳遞的類型參數移動到另一個接口,因為它可以在其他地方重用。 當然,您可以根據您的應用程序對其進行調整,

interface ItemProps {
  ISIN: string;
  rate: number;
}

type ItemComponent = ComponentType<ItemProps>

// for the renderer
type Props = {
  Item: ItemComponent;
  // rest
}

暫無
暫無

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

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