【问题标题】:How to define specific return type of react method (typescript)如何定义react方法的具体返回类型(打字稿)
【发布时间】:2019-03-20 20:34:10
【问题描述】:

我想定义一个特定反应组件的返回类型。

例如:

组件 1

class ComponentFoo extends React.Component<any, any> {
   public render() {…}
}

组件 2

class ComponentBar extends React.Component<any, any> {
    public renderComponentFoo() : ComponentFoo { <---
      return <ComponentFoo />
    }

    public render() {
      …
      {this.renderComponentFoo()}
      …
    }
}

这样的事情可能吗?

【问题讨论】:

  • 这似乎不是正确的 TypeScript。
  • 你能更精确一点吗?你有什么问题?并发症错误?
  • 在你的情况下是否重要,为什么不使用any 作为返回类型?
  • 我需要一个特定的类型。快速示例:我在 React 中构建了一个表。并且Table head需要是class TableHead extends React.Component…的组件类型
  • TypeScript 无法像这样区分实例化的 JSX 节点。有an open issue to track this functionality,但这将是一个重大更改,因此必须仔细考虑。

标签: reactjs typescript jsx typescript-typings


【解决方案1】:

您的renderComponentFoo 方法应该返回React.ReactNode

JSX/TSX 只是 React.createElement() 周围的语法糖,它返回 React.ReactNode。您没有像当前代码所建议的那样返回 ComponentFoo 的实例。

【讨论】:

    猜你喜欢
    • 2019-09-08
    • 2019-12-06
    • 2020-05-09
    • 2018-07-01
    • 2021-05-16
    • 2016-11-11
    • 2021-08-15
    • 2020-06-29
    • 1970-01-01
    相关资源
    最近更新 更多