微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

打字稿未在 forwardRef 中解析 JSX

如何解决打字稿未在 forwardRef 中解析 JSX

我正在 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 />) }

也没有用,同样的错误

在这里遗漏了什么?

解决方法

我遗漏了一些非常明显的东西:)

只需将文件名从 .ts 重命名为 .tsx

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。