【发布时间】: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