[英]Typescript not parsing JSX inside forwardRef
I'm working with React and Next.js in Typescript and I'm trying to make this wrapper component that will bundle together a Next.js <Link />
component and a <a />
tag:我正在 Typescript 中使用 React 和 Next.js 并且我正在尝试制作这个包装器组件,它将捆绑在一起
<a />
标签: <Link />
组件和 <a
import React, { forwardRef } from 'react';
import Link, { LinkProps } from 'next/link';
type EnhancedLinkProps = {
children: React.ReactNode[];
} & LinkProps;
const EnhancedLink = forwardRef<HTMLAnchorElement, EnhancedLinkProps>(({
as,
passHref,
prefetch,
replace,
shallow,
scroll,
href,
children,
...rest
}, ref) => (
<Link
href={href}
as={as}
passHref={passHref}
prefetch={prefetch}
replace={replace}
shallow={shallow}
scroll={scroll}
href={href}
>
<a {...rest} ref={ref}>
{children}
</a>
</Link>
))
export default EnhancedLink;
Problem is that I want to support forwarding refs, but as soon as I wrap my function in forwardRef typescript fails to parse my JSX.问题是我想支持转发引用,但是一旦我将 function 包装在 forwardRef typescript 中,就无法解析我的 JSX。 I get this error message on the line with
<Link...
:我在
<Link...
行收到此错误消息:
"'Link' refers to a value, but is being used as a type here. Did you mean 'typeof Link'?ts(2749)"
Seems like it is maybe registering the <>
around Link as Typescript syntax.似乎它可能正在将 Link 周围的
<>
注册为 Typescript 语法。
I used this example to set up my forwardRef as typescript code:我使用此示例将我的 forwardRef 设置为 typescript 代码:
type Props = { children: React.ReactNode; type: "submit" | "button" };
export type Ref = HTMLButtonElement;
export const FancyButton = React.forwardRef<Ref, Props>((props, ref) => (
<button ref={ref} className="MyClassName" type={props.type}>
{props.children}
</button>
));
Taken from here .取自这里。 I was assuming that the example should be good, but when I copy paste that directly into my code, I also get an error on the line where the JSX starts (ie
<button>...
):我假设该示例应该很好,但是当我将其直接复制粘贴到我的代码中时,我在 JSX 开始的行(即
<button>...
)上也出现错误:
"Cannot find name 'button'.ts(2304)"
Button is just a good old HTML element, so it's definitely not picking up the JSX here either. Button 只是一个很好的旧 HTML 元素,所以它也绝对不会在这里使用 JSX。
I tried rewriting the arrow function with a explicit return statement.我尝试使用显式返回语句重写箭头 function。 From:
从:
() => (<button />)
To:至:
() => { return (<button />) }
Did not work either, same error.也没用,同样的错误。
What am I missing here?我在这里想念什么?
I was missing something very obvious:)我错过了一些非常明显的东西:)
The filename just had to be renamed from .ts
to .tsx
.文件名只需从
.ts
重命名为.tsx
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.