React报错之React.Children.only expected to receive single React element child
总览
当我们把多个子元素传递给一个只期望有一个React子元素的组件时,会产生"React.Children.only expected to receive single React element child"错误。为了解决该错误,将所有元素包装在一个React片段或一个封闭div中。
这里有个示例来展示错误是如何发生的。
// App.js
import React from 'react';
function Button(props) {
  // ️ expects single child element
  return React.Children.only(props.children);
}
export default function App() {
  return (
    <Button>
      <button
        onClick={() => {
          console.log('Button clicked');
        }}
      >
        Click
      </button>
      <button
        onClick={() => {
          console.log('Button clicked');
        }}
      >
        Click
      </button>
    </Button>
  );
}
Button元素期望传递单个子元素,但我们在同级下传递了2个子元素。
React片段
我们可以使用React片段来解决该错误。
import React from 'react';
function Button(props) {
  // ️ expects single child element
  return React.Children.only(props.children);
}
export default function App() {
  return (
    <Button>
      <>
        <button
          onClick={() => {
            console.log('Button clicked');
          }}
        >
          Click
        </button>
        <button
          onClick={() => {
            console.log('Button clicked');
          }}
        >
          Click
        </button>
      </>
    </Button>
  );
}
当我们需要对子节点列表进行分组,而不需要向DOM添加额外的节点时,就会使用Fragments。
你可能还会看到使用了更详细的片段语法。
import React from 'react';
function Button(props) {
  // ️ expects single child element
  return React.Children.only(props.children);
}
export default function App() {
  return (
    <Button>
      <React.Fragment>
        <button
          onClick={() => {
            console.log('Button clicked');
          }}
        >
          Click
        </button>
        <button
          onClick={() => {
            console.log('Button clicked');
          }}
        >
          Click
        </button>
      </React.Fragment>
    </Button>
  );
}
上面的两个例子达到了相同的结果--它们对子元素列表进行分组,而没有向DOM中添加额外的节点。
现在大多数代码编辑器都支持更简明的语法,因此更常用。
DOM元素
另一个解决方案是将子元素包裹在另一个DOM元素中,例如一个div。
import React from 'react';
function Button(props) {
  // ️ expects single child element
  return React.Children.only(props.children);
}
export default function App() {
  return (
    <Button>
      <div>
        <button
          onClick={() => {
            console.log('Button clicked');
          }}
        >
          Click
        </button>
        <button
          onClick={() => {
            console.log('Button clicked');
          }}
        >
          Click
        </button>
      </div>
    </Button>
  );
}
这样就解决了错误,因为我们现在向Button组件传递了单一的子元素。
这种方法只有在添加一个额外的
div而不会破坏你的布局时才有效,否则就使用一个片段,因为片段不会向DOM添加任何额外的标记。
这是很有必要的,因为Button组件使用React.Children.only函数来验证children属性是否只有一个子元素,并返回它。否则该方法会抛出一个错误。
React.Children.only方法经常被用于第三方库,以确保API的消费者在使用该组件时只提供一个子元素。
React报错之React.Children.only expected to receive single React element child的更多相关文章
- react 报错的堆栈处理
		react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ... 
- React报错之Expected `onClick` listener to be a function
		正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ... 
- React报错 :browserHistory doesn't exist in react-router
		由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ... 
- react报错 TypeError: Cannot read property 'setState' of undefined
		代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ... 
- React报错之Cannot find name
		正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ... 
- React报错之Cannot find namespace context
		正文从这开始~ 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig. ... 
- React报错之Functions are not valid as a React child
		正文从这开始~ 总览 产生"Functions are not valid as a React child. This may happen if you return a Compone ... 
- React报错之Parameter 'props' implicitly has an 'any' type
		正文从这开始~ 总览 当我们没有为函数组件或者类组件的props声明类型,或忘记为React安装类型声明文件时,会产生"Parameter 'props' implicitly has an ... 
- React报错:Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix,
		今天在开发时报了以下错误,记录一下 我们不能在组件销毁后设置state,防止出现内存泄漏的情况 出现原因直接告诉你了,组件都被销毁了,还设置个锤子的state啊 解决方案: 利用生命周期钩子函数:co ... 
- react报错this.setState is not a function
		当报错这个的时候就要看函数是否在行内绑定this,或者在constructor中绑定this. 我这里犯的错误的是虽然我在constructor中绑定了this,但是语法写的不正确. 错误示范: co ... 
随机推荐
- 某云负载均衡获取客户端真实IP的问题
			某云负载均衡真实IP的问题,我们这边已经遇到过两次了.而且每次和售后沟通的时候都大费周折,主要是要给售后说明白目前文档的获取真实IP是有问题的,他们觉得文档上说明的肯定没问题,售后要是不明白,他们不会 ... 
- 集合框架——LinkedList集合源码分析
			目录 示例代码 底层代码 第1步(初始化集合) 第2步(往集合中添加一个元素) 第3步(往集合中添加第二个元素) 第4步(往集合中添加第三个元素) LinkedList添加元素流程示意图 第5步(删除 ... 
- 锐捷网关交换机开启dhcp服务
			锐捷网关交换机作为dhcp server: Ruijie(config)#service dhcp ------>该命令默认不启用,交换机必须配置 Ruijie(config)#i ... 
- 洛谷P7167  [eJOI 2020 Day1] Fountain (单调栈+ST)
			开两个数组:to[i][j]表示从i这个位置向下的第2j个圆盘是哪个,f[i][j]表示流满从i这个位置向下的 2j 个圆盘需要多少体积的水. 详情见代码: 1 #include<bits/st ... 
- Maximum Entropy Population-Based Training for Zero-Shot Human-AI Coordination
			原文:https://www.cnblogs.com/Twobox/p/16791412.html 熵 熵:表述一个概率分布的不确定性.例如一个不倒翁和一个魔方抛到地上,看他们平稳后状态.很明显,魔方 ... 
- 服务器之Apollo单机部署(快速安装)
			部署Apollo apollo单机部署(快速安装) Apollo官网:https://www.apolloconfig.com/#/zh/deployment/quick-start-docker 官 ... 
- 5.-GET请求和POST请求
			一.定义 无论是GET请求还是POST,统一由视图函数接收请求,通过判定request.method区分具体的请求动作 二.GET处理 GET请求方式中,如果有数据需要传递给服务器,通常会用查 ... 
- 二十八、Helm
			使用Helm3管理复杂应用的部署 认识Helm 为什么有helm? Helm是什么? kubernetes的包管理器,"可以将Helm看作Linux系统下的apt-get/yum" ... 
- Mybatis 报错Mapper method 'xxx' has an unsupported return type
			报错原因: 出现这种错误,说明sql语句执行成功,只是返回类型出了问题. 解决方法: insert.delete.update操作默认返回一个int类型的整数,将增删改的接口改成int或者void即可 ... 
- springboot的全局异常处理类
			import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import or ... 
