【问题标题】:How to declare type for functional React component using object destructuring in props?如何使用道具中的对象解构为功能性 React 组件声明类型?
【发布时间】:2020-08-20 01:54:24
【问题描述】:

我仍在学习 TypeScript 和声明(高级)类型。我正在尝试将我的 CRA 项目转换为打字稿,并且其中包含以下组件。我应该如何为此声明类型?

这个组件与 react-router-dom 示例几乎是 1:1 的,但我找不到任何用 TypeScript 编写的示例

// ProtectedContent.tsx

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import Auth from '../services/Auth';

const ProtectedContent = ({ component: Component, ...rest }) => {
  return (
    <Route {...rest} render={(props) => {
      if (Auth.isAuthenticated()) {
        return (
          <Component {...props} />
        );
      } else {
        return (
          <Redirect to={{
            pathname: '/auth/signin',
            state: { from: props.location },
          }} />
        );
      }
    }} />
  );
};

export default ProtectedContent;

我尝试为参数创建一个接口:

interface PCProps extends HTMLAttributes<HTMLElement>{
  component: React.Component;
}

const ProtectedContent = ({ component: Component, ...rest }: PCProps) => {
   // .......
}

但后来我遇到了线路问题

return (
  <Component {...props} />
);

因为有错误说

JSX 元素类型“组件”没有任何构造或调用签名。 ts(2604)

然后当我试图解决这个问题时,我最终掉进了一个疯狂的兔子洞,失去了对正在发生的事情的追踪和理解。

那么我应该如何声明它的类型,以便组件可以是任何 React 组件,然后巧妙地解构其余的道具?

TS 版本为 3.8.3


编辑:(可能的解决方案)

我从互联网的深处找到了这个“解决方案”。我可以将 PCProps 接口中的组件声明为“ReactType”并像这样使用它:

interface PCProps {
  component: React.ReactType;
}

const ProtectedContent = ({ component: Component, ...rest }): PCProps => {
  ...
}

这将消除错误,但为什么呢?这个'ReactType'是什么?我浏览了文档,没有发现任何相关的内容。有没有 React 和 TS 方面经验丰富的人可以解释这一点以及应该如何键入这种组件?

我不太喜欢使用这个解决方案,因为我不知道发生了什么。

Solution source


编辑2:

显示使用 React.FC 的原始建议解决方案和使用 React.ReactType 的可能解决方案的沙盒。检查此沙箱中的所有三个文件。

Sandbox for this question

【问题讨论】:

  • my project 我最近是这样做的:export interface PrivateRouteProps extends RouteProps, StateProps {}
  • 您能否确认您的文件扩展名是 .tsx 而不是 .ts?
  • @gqstav 是的,文件扩展名为 .tsx
  • @AlexanderDerck 你能解释一下你的解决方案吗?
  • 好的,尝试声明 component: React.FC; 在这里可以正常工作:codesandbox.io/s/silly-hamilton-1xuyu?file=/src/App.tsx:95-97

标签: javascript reactjs typescript typescript-typings react-props


【解决方案1】:

确保您的文件扩展名是.tsx 而不是.ts,并且您声明的是component: React.FC;。工作示例:codesandbox.io/s/silly-hamilton-1xuyu?file=/src/App.tsx:95-97

【讨论】:

  • 是强制性的吗?
  • 嗯,.ts 文件是普通的旧 Typescript 文件,不支持添加 JSX 元素,例如 component 在这种情况下。
  • 我猜不建议但我们仍然可以使用它。
猜你喜欢
  • 2023-01-15
  • 2020-08-23
  • 2021-06-20
  • 1970-01-01
  • 2019-12-25
  • 2021-10-22
  • 1970-01-01
  • 2019-11-01
  • 2021-10-15
相关资源
最近更新 更多