【问题标题】:TypeScript React Function Component name as typeTypeScript React 函数组件名称作为类型
【发布时间】:2019-11-09 09:27:54
【问题描述】:

在React.js中,我有一个Function Component,当我使用函数名作为type时,得到一个错误。

代码示例:

import * as React from "react";
import { render } from "react-dom";

interface NameViewProps {
  name: string;
}
function NameView({ name }: NameViewProps) {
  return <div>{name}</div>;
}

interface Props {
  // ts error: Cannot find name 'NameView'.ts(2304)
  children: NameView[];
}

class Demo extends React.Component<Props> {
  render() {
    return (
      <div>
        <h2>in demo component with children div array</h2>
        {this.props.children}
      </div>
    );
  }
}

如何将函数组件的名称用作type?

你可以试试codesandbox here

【问题讨论】:

  • 那个类型应该是什么意思?将函数用作类型是没有意义的。
  • 你想如何使用Demo?为什么要将其子项限制为特定类型?
  • @AsukaSong 我认为如果可以的话,最好为children 提供一个特定的类型。所以我们可以防止我们组件的用户传递错误的孩子。
  • @MuratKaragöz 我想限制 Demo 组件只接受 NameView 组件的子组件,而不是像 div 或 span 这样的其他组件。

标签: reactjs typescript


【解决方案1】:

使用 typeof(函数名),即 typeof NameView

【讨论】:

    【解决方案2】:
    interface Props {
      children: (typeof NameView)[];
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 2019-05-20
      • 2021-07-11
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 2017-06-03
      • 2019-07-25
      • 2019-11-18
      相关资源
      最近更新 更多