【问题标题】:NextJS 9.3 Link not a constructor function for JSX elementsNextJS 9.3 链接不是 JSX 元素的构造函数
【发布时间】:2020-04-26 13:27:30
【问题描述】:

尝试创建一个 Link 元素,其中包含一个标题和一个用于 href 的 slug。

import React from 'react';
import Link from 'next/link';
import styled from 'styled-components';

type Props = {
  title: string;
  slug: string;
};

const NavElement = ({ title, slug }: Props) => {
  return (
    <Link href={slug}>
      <a>{title}</a>
    </Link>
  );
};

export default NavElement;

package.json 中的依赖项

  "dependencies": {
    "@types/react": "^16.9.34",
    "@types/styled-components": "^5.1.0",
    "axios": "^0.19.2",
    "contentful": "^7.14.3",
    "moment": "^2.24.0",
    "next": "9.3.5",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-lottie": "^1.2.3",
    "styled-components": "^5.1.0"
  }

得到这个错误:

JSX element type 'Link' is not a constructor function for JSX elements.
  Type 'Link' is missing the following properties from type 'ElementClass': context, setState, forceUpdate, props, and 2 more.ts(2605)
JSX element class does not support attributes because it does not have a 'props' property.ts(2607)

通过 nextjs 文档和以前的案例,我已经完成了它,并且我一生都无法发现问题所在。有什么建议吗?

【问题讨论】:

    标签: reactjs typescript next.js


    【解决方案1】:

    如果你用大括号括起来,你会丢失一个 return 语句

    试试这个...

    const NavElement = ({ title, slug }: Props) => (
      <Link href={slug}>
        <a>{title}</a>
      </Link>;
    );
    

    或者这个

    const NavElement = ({ title, slug }: Props): JSX.Element => {
      return (
        <Link href={slug}>
          <a>{title}</a>
        </Link>
      );
    };
    

    【讨论】:

    • 同样的问题仍然存在。尽管已更新为有效的观察表单代码格式化透视图。
    • 那绝对应该。在我的下一个服务器上进行了相同的测试,并且效果很好。尝试重新启动您的服务器。
    • 或者尝试显式定义函数的返回类型,看看是否收到打字稿警告。 const NavElement = ({ title, slug }: Props): JSX.Element =&gt; {
    • 没有变化。我猜它与依赖关系有关。也许是某种冲突..
    • 你能提供一个复制链接吗?刚刚在我的 Nextjs 项目中尝试了相同的代码。运行"next": "9.3.2"
    猜你喜欢
    • 2019-11-24
    • 2020-05-31
    • 2020-07-01
    • 2019-05-29
    • 2019-03-06
    • 2019-05-18
    • 1970-01-01
    • 2020-09-16
    • 2019-07-21
    相关资源
    最近更新 更多