【问题标题】:Typescript with React: Set type of rendered react componentTypescript with React:设置渲染反应组件的类型
【发布时间】:2019-11-21 03:16:16
【问题描述】:

如何在 Typescript 中设置渲染的 React 组件的类型? 例如: 我有一些 React 类:

const Test: React.FunctionComponent<{}> = (): JSX.Element = (
  <div>some text</div>
);

如果我们像这样安慰它:

console.log(<Test />)

我们得到如下结果:

{
  $$typeof: Symbol(react.element),
  ...
  type: {
    name: 'Test'
  }
}

如果我想将此渲染组件作为道具传递并且我有这样的打字稿界面:

interface Props {
  test: JSX.Element | React.ReactNode
}

能否我指定Test组件的这个渲染结果的类型,例如这是组件Test的一个实例(我知道JSX.Element不是泛型的,它只是一个抽象的例子):

interface Props {
  test: JSX.Element<Test>
}

【问题讨论】:

  • 你不能做JSX.Element&lt;anything really&gt; 因为Element 不是通用的。但我的问题是你想用这个实现什么?
  • 如果我们有像 JSX.Element 这样的类型,我们可以将任何东西传递给 props,我的意思是任何渲染的组件,但是我们需要非常特殊的类型,比如 typeof Test。是的,我知道 JSX.Element 不是通用的。只是举例

标签: reactjs typescript


【解决方案1】:

您可以定义一个接口并像这样使用它:

// This could be JSX.Element or whatever
interface SomeReactComponent {
  A: string;
} 

interface SomeOtherComponent extends SomeReactComponent {
  B: number;
}

const CompA: SomeReactComponent = { A: "123" };
const CompB: SomeOtherComponent = { A: "123", B: 123 };
const anythingElse: number | string | symbol | object = 1;

const someOtherComponent = (input: SomeOtherComponent) => {
  console.log(input);
};

someOtherComponent(CompA); // Won't compile
someOtherComponent(CompB); // OK
someOtherComponent(anythingElse); // Won't compile either

所以在你的情况下extending React.FunctionComponent&lt;{}&gt; 应该可以工作。

一个小陷阱:如果您要走这条路,您必须确保您的接口不是空的或相同的。这意味着简单地用空接口扩展 React.Component 是行不通的。

【讨论】:

    猜你喜欢
    • 2020-09-18
    • 2020-07-07
    • 2021-07-22
    • 2020-08-12
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多