总览

当我们把多个子元素传递给一个只期望有一个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的更多相关文章

  1. react 报错的堆栈处理

    react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...

  2. React报错之Expected `onClick` listener to be a function

    正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...

  3. React报错 :browserHistory doesn't exist in react-router

    由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...

  4. react报错 TypeError: Cannot read property 'setState' of undefined

    代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ...

  5. React报错之Cannot find name

    正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...

  6. React报错之Cannot find namespace context

    正文从这开始~ 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig. ...

  7. 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 ...

  8. React报错之Parameter 'props' implicitly has an 'any' type

    正文从这开始~ 总览 当我们没有为函数组件或者类组件的props声明类型,或忘记为React安装类型声明文件时,会产生"Parameter 'props' implicitly has an ...

  9. 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 ...

  10. react报错this.setState is not a function

    当报错这个的时候就要看函数是否在行内绑定this,或者在constructor中绑定this. 我这里犯的错误的是虽然我在constructor中绑定了this,但是语法写的不正确. 错误示范: co ...

随机推荐

  1. SECS半导体设备通讯-1 SECS的基本概念

    一 什么是SECS SECS(SEMI Equipment Communication Standard),半导体设备通讯标准. 此标准由SEMI (Semiconductor Equipment a ...

  2. 文盘Rust -- struct 中的生命周期

    最近在用rust 写一个redis的数据校验工具.redis-rs中具备 redis::ConnectionLike trait,借助它可以较好的来抽象校验过程.在开发中,不免要定义struct 中的 ...

  3. java的分页原理详解

    首先先创建一个Student实体类. import java.io.Serializable; import java.util.Map; public class Student implement ...

  4. 计算机网络(Learning Records)

    背景:没想到本专业并不开设这门课程,感觉过于逆天,之前开发的时候了解过相关知识 但是从来没有系统地学过,就自己看了书,总结一下 参考:<TCP/IP详解 卷1:协议> 概述 大多数网络应用 ...

  5. Double数据运算过程中精度调整

    Double数据进行运算时,容易出现多位小数的精度问题 ①问题现象 ②解决方案 使用BigDecimal类型来进行Double类型数据运算 创建BigDecimal类型对象时将Double类型的数据转 ...

  6. 15 Uncaught TypeError: Cannot set properties of null (setting ‘onclick‘)

    1.报错的代码 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <t ...

  7. Codeforces Round #832 (Div. 2) A-D

    比赛链接 A 题解 知识点:贪心. 我们考虑把正数和负数分开放,显然把负数和正数放在一起的结果不会更优. 时间复杂度 \(O(n)\) 空间复杂度 \(O(1)\) 代码 #include <b ...

  8. 禁止eslint对指定代码检测

    有时候我们引入外部文件的API时,eslint无法识别,编译的时候就会出现warn eslint是可以禁用对指定代码的检测: 单行注释 let map = new BMap.Map('map') // ...

  9. tools2

    [对身份证的校验] //身份证的校验 import java.util.stream.IntStream; /** * 身份证号码验证 * 1.号码的结构 * 公民身份号码是特征组合码,由十七位数字本 ...

  10. Go语言核心36讲26

    你好,我是郝林.今天我分享的主题是测试的基本规则和流程的(下)篇. Go语言是一门很重视程序测试的编程语言,所以在上一篇中,我与你再三强调了程序测试的重要性,同时,也介绍了关于go test命令的基本 ...