javascript - Next.js:错误:React.Children.only 期望接收单个 React 元素子元素

标签 javascript html reactjs frontend next.js

我有一个名为 Nav 的组件里面components目录及其代码如下所示:

import Link from 'next/link';

const Nav = () => {
    return(
        <div>
            <Link href="/">  <a> Home </a> </Link>
            <Link href="/about"> <a> About </a>  </Link>
        </div>
    )
}

export default Nav;

这给了我错误:

Error: React.Children.only expected to receive a single React element child.

但是如果我删除 <a> <Link> 内的标签组件,我可以查看页面,但随后在控制台中我收到警告:

Warning: You're using a string directly inside <Link>. This usage has been deprecated. Please add an <a> tag as child of <Link>

那么我在这里做错了什么?

最佳答案

此问题是由于 <Link> 之间的空格造成的标签和<a>标签。

因此更改您的代码,例如,

        <div>
            <Link href="/"><a> Home </a></Link>
            <Link href="/about"><a> About </a></Link>
        </div>

变更原因:

-> The <Link> can have only one child node and here the space between the link and a tag are considered as a child nodes.

-> So there are two child nodes (One is space and another is <a> tag) which is invalid and hence such error occurs.

关于javascript - Next.js:错误:React.Children.only 期望接收单个 React 元素子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61651497/

相关文章:

javascript - this.props 在 React 组件中的箭头函数中显示为未定义

Javascript:如何从子窗口刷新父窗口

javascript - 为什么点击一个元素会提示点击它旁边的复选框?

html - 将 pdf 文件嵌入 html 并允许下载

javascript - react : setState method is not executed

javascript - React Native 将 JSON 对象转换为数组

reactjs - 在 ELK (Logstash) 中记录客户端/Javascript 的最佳方式

javascript - 使用 webpack 的 Angular 2 测试 karma 找不到变量 : Map

html - 响应式导航,无法以百分比定义宽度/高度

Javascript 将 ID 添加到 HTML href