我正在尝试在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 **
发布于 2019-05-07 00:15:44
该错误意味着JSX语法不是这样解析的:
lib/auth.ts:44:30 -错误TS1005:'>‘。
44返回<包装组件{...this.props} />;
为此,应将auth.ts重命名为auth.tsx。如果为JSX正确配置了TypeScript,这是唯一需要修复的地方。
发布于 2019-06-27 01:22:47
我也犯了同样的错误,但原因不同。我在前一行中注释掉了一个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/
https://stackoverflow.com/questions/55679552
复制相似问题