首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Typescript中创建React HOC时出错

在Typescript中创建React HOC时出错
EN

Stack Overflow用户
提问于 2019-04-15 04:06:01
回答 2查看 3.4K关注 0票数 7

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

但我得到了一个错误。首先,VSCode对此提出了抱怨

代码语言:javascript
复制
'WrappedComponent' refers to a value, but is being used as a type here.

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

代码语言:javascript
复制
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组件的代码**

代码语言:javascript
复制
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 **

EN

回答 2

Stack Overflow用户

发布于 2019-05-07 00:15:44

该错误意味着JSX语法不是这样解析的:

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

44返回<包装组件{...this.props} />;

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

票数 31
EN

Stack Overflow用户

发布于 2019-06-27 01:22:47

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

代码语言:javascript
复制
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.

我最终通过更改注释来修复它,如下所示:

代码语言:javascript
复制
  {/*
  <SomeJSXTag />
  */}
  <WrappedComponent /> --- Error Disappeared

错误就消失了。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55679552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档