我正在 Typescript 中使用 React 和 Next.js,我正在尝试制作这个包装器组件,它将一个 Next.js <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;
问题是我想支持转发引用,但是一旦我将函数包装在 forwardRef 打字稿中,就无法解析我的 JSX。我在使用 <Link...
时收到此错误消息:
"'Link' refers to a value, but is being used as a type here. Did you mean 'typeof Link'?ts(2749)"
似乎可能将 Link 周围的 <>
注册为 Typescript 语法。
我使用这个例子将我的 forwardRef 设置为打字稿代码:
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>
));
取自here。我假设该示例应该很好,但是当我将其直接复制粘贴到我的代码中时,我还在 JSX 开始的行(即 <button>...
)上收到错误消息:
"Cannot find name 'button'.ts(2304)"
Button 只是一个很好的旧 HTML 元素,所以它绝对不会在这里选择 JSX。
我尝试用显式返回语句重写箭头函数。来自:
() => (<button />)
致:
() => { return (<button />) }
也没有用,同样的错误。
我在这里遗漏了什么?
答案 0 :(得分:0)
我遗漏了一些非常明显的东西:)
只需将文件名从 .ts
重命名为 .tsx
。