【问题标题】:Type for a React component with certain props为带有特定 props 的 React 组件输入类型
【发布时间】:2020-06-20 09:15:23
【问题描述】:

我想表达一个组件的类型,它需要某些道具:

作为一个例子,我想渲染任何接受 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&lt;{ISIN: string, rate: number}&gt;, 但这仅允许 function 组件,而不是基于 class 的组件。

是否有一个通用类型可以同时满足这两种情况?

【问题讨论】:

    标签: reactjs typescript typescript-typings


    【解决方案1】:

    是的,React.ComponentType。这是它的类型定义。它需要一个用于 props 的泛型类型参数。

    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>;
    };
    

    P.S.- 我建议将类型参数传递给另一个接口,因为它可以在其他地方重用。当然,您可以根据自己的应用对其进行调整,

    interface ItemProps {
      ISIN: string;
      rate: number;
    }
    
    type ItemComponent = ComponentType<ItemProps>
    
    // for the renderer
    type Props = {
      Item: ItemComponent;
      // rest
    }
    
    

    【讨论】:

      猜你喜欢
      • 2022-11-17
      • 2021-11-20
      • 2018-12-01
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 2017-11-08
      • 2020-10-07
      • 2019-11-02
      相关资源
      最近更新 更多