1

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:

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. I get this error message on the line with <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.

I used this example to set up my forwardRef as typescript code:

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 (i.e. <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.

I tried rewriting the arrow function with a explicit return statement. From:

() => (<button />)

To:

() => { return (<button />) }

Did not work either, same error.

What am I missing here?

4

1 回答 1

1

我错过了一些非常明显的东西:)

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

于 2021-04-27T16:59:26.047 回答