【问题标题】:Getting error when creating React HOC in Typescript在 Typescript 中创建 React HOC 时出错
【发布时间】:2023-03-04 20:58:01
【问题描述】:

我正在尝试在 Typescript 中创建和编译 React Higer Order 组件。

但是我得到一个错误。首先VSCode抱怨这个

'WrappedComponent' refers to a value, but is being used as a type here.

** 而我的 Typescript 编译器会抛出这个错误。**

lib/auth.ts:44:30 - error TS1005: '>' expected.

44     return <WrappedComponent {...this.props} />;
                                ~

lib/auth.ts:44:47 - error TS1109: Expression expected.

44     return <WrappedComponent {...this.props} />;
                                                 ~

lib/auth.ts:44:48 - error TS1109: Expression expected.

44     return <WrappedComponent {...this.props} />;

**这是我下面的 React HOC 组件代码**

import * as React from 'react';
import Router from 'next/router';
import { NextContext } from 'next';
import nextCookie from 'next-cookies';
import { MOVED_TEMPORARILY } from 'http-status-codes';

interface ComponentExtra extends React.Component, React.SFC {
  getInitialProps: Function;
}

export const withAuthSync = (WrappedComponent: ComponentExtra) => class extends React.Component {
  static async getInitialProps(ctx: NextContext) {
    const token = auth(ctx);
    const componentProps = WrappedComponent.getInitialProps && (await WrappedComponent.getInitialProps(ctx));
    return { ...componentProps, token };
  }

  render() {
    return <WrappedComponent {...this.props} />;
  }
};

export const auth = (ctx: NextContext) => {
  const { req, res } = ctx;
  const { token } = nextCookie(ctx);

  if (req && res && !token) {
    res.writeHead(MOVED_TEMPORARILY, { Location: '/signin' }).end();
    return;
  }

  return token;
};

**更新错误是由于文件扩展名不是.tsx而是.ts **

【问题讨论】:

  • 我忘了说错误发生在render函数返回行
  • 错误说明了什么?编辑您的问题并添加错误日志和错误行号,以及编辑器中的任何编译时错误(如果有任何 TSLint 设置)
  • 问题应该包含stackoverflow.com/help/mcve。这段代码没有使用 WrappedComponent 作为类型,不会导致这个错误。
  • 它没有被解析为 JSX 语法,这就是问题所在。对于初学者,它应该是 auth.tsx 而不是 auth.ts。如果 TS 配置正确,这是唯一需要的修复。
  • 天哪,这就是问题所在。非常感谢@estus

标签: reactjs typescript


【解决方案1】:

这个错误意味着 JSX 语法没有被这样解析:

lib/auth.ts:44:30 - 错误 TS1005: '>' 预期。

44     return <WrappedComponent {...this.props} />;

为此,应将 auth.ts 重命名为 auth.tsx。如果 TypeScript 为 JSX 正确配置,这是唯一需要的修复。

【讨论】:

    【解决方案2】:

    我遇到了同样的错误,但原因不同。我在上一行中注释掉了一个 JSX 元素,如下所示:

    file1.tsx
      export const WrappedComponent = HocFunction(Component);
    
    
    file2.tsx
      import { WrappedComponent }  from './file1.tsx';
      ...
      // <SomeJSXTag />
      <WrappedComponent /> --- Error: 'WrappedComponent' refers to a value, but is being used as a type here.
    

    我最终通过将评论更改为如下所示来修复它:

      {/*
      <SomeJSXTag />
      */}
      <WrappedComponent /> --- Error Disappeared
    

    错误消失了。

    目前,这可能只是 JSX 行为:https://wesbos.com/react-jsx-comments/

    【讨论】:

      猜你喜欢
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多