我正在尝试在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 **
答案 0 :(得分:1)
该错误意味着未将JSX语法解析为这样:
lib / auth.ts:44:30-出现错误TS1005:“>”。
44 return <WrappedComponent {...this.props} />;
为此,应将auth.ts重命名为auth.tsx。如果为JSX正确配置了TypeScript,则这是唯一需要的修复程序。
答案 1 :(得分:0)
我有相同的错误,但是原因不同。我在上一行中注释了一个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/