Next.js:错误:React.Children.only 预期接收单个 React 元素子项 [英] Next.js: Error: React.Children.only expected to receive a single React element child
问题描述
我在 components
目录中有一个名为 Nav
的组件,它的代码如下所示:
从'next/link'导入链接;常量导航 = () =>{返回(<链接href="/"><a>主页 </a></链接><链接href="/about"><a>关于</a></链接></div>)}导出默认导航;这给了我错误:
错误:React.Children.only 期望接收单个 React 元素子元素.
但是如果我删除 <Link>
组件中的 <a>
标记,我可以查看页面,但是在控制台中我得到一个警告:
警告:您在 <Link> 中直接使用字符串.此用法已被弃用.请添加一个 <a>标记为 <Link>
的子级那么我在这里做错了什么?
解决方案 这个问题是由于<Link>
标签和之间的空格造成的.一个>
标签.
所以改变你的代码,
<div><Link href="/"><a>主页 </a></链接><Link href="/about"><a>关于 </a></Link></div>
更改原因:
<块引用>-> <Link>
只能有一个子节点,这里 link
和 a
标签之间的空间被认为是一个子节点.
-> 所以有两个子节点(一个是空格,另一个是 <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 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.
这篇关于Next.js:错误:React.Children.only 预期接收单个 React 元素子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文