Next.js:错误:React.Children.only 期望接收单个 React 元素子元素 [英] Next.js: Error: React.Children.only expected to receive a single React element child
问题描述
我在 components
目录中有一个名为 Nav
的组件,它的代码如下所示:
从'next/link'导入链接;const Nav = () =>{返回(<div><Link href="/"><a>主页</链接><Link href="/about"><a>关于</a></链接>
)}导出默认导航;
这给了我错误:
错误:React.Children.only 期望接收单个 React 元素子元素.
但是如果我删除 组件中的
<a>
标签,我可以查看页面,但是在控制台中我得到一个警告:
警告:您直接在 <Link> 中使用字符串.此用法已被弃用.请添加一个<a>标记为
那么我在这里做错了什么?
这个问题是由于 之间的空格造成的.> 标签和
标签.
所以改变你的代码,
<Link href="/"><a>主页 </a></Link><Link href="/about"><a>关于</a></Link>
变更原因:
<块引用>-> 只能有一个子节点,这里
link
和 a
标签之间的空间被认为是一个子节点.
-> 所以有两个子节点(一个是空间,另一个是 标签)是无效的,因此发生了这样的错误.
I'm having a component called Nav
inside components
directory and it's code is some thing like below:
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;
This gives me the error:
Error: React.Children.only expected to receive a single React element child.
But if I remove the <a>
tags within <Link>
components, I can view the pages, but then in the console I'm getting a warning of:
Warning: You're using a string directly inside <Link>. This usage has been deprecated. Please add an <a> tag as child of <Link>
So what am I doing wrong here?
This issue is due to the space between <Link>
tag and <a>
tag.
So change your code like,
<div>
<Link href="/"><a> Home </a></Link>
<Link href="/about"><a> About </a></Link>
</div>
Reason for the change:
-> The
<Link>
can have only one child node and here the space between thelink
anda
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.
这篇关于Next.js:错误:React.Children.only 期望接收单个 React 元素子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!