错误React.Children.only仅预期接收单个React元素的孩子 [英] Error React.Children.only expected to receive a single React element child

查看:119
本文介绍了错误React.Children.only仅预期接收单个React元素的孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不能完全确定我的应用程序在这里出了什么问题.我正在使用create-react-app,并且尝试将所有组件呈现到各自的根div中.问题是,我能够将除最后一个得分组件之外的所有组件呈现到页面上.我什至尝试将该组件放入div中,但仍然遇到以下问题:

Not entirely sure what went wrong in my app here. I'm using create-react-app, and I'm trying to render all of my components into the respective root div. Problem is, I'm able to render all of the components onto the page except the very last one, the Score component. I've even tried throwing that component into a div and I'm still getting the following issue:

"React.Children.仅预期接收单个React元素的孩子".

'React.Children.only expected to receive a single React element child'.

这到底是什么意思?

这是我的App.js结构.

Here's my App.js structure.

render() {
   return (
       <div className="App">
           <div className="App-header">
              <h2>BAO BAO BAO</h2>
           </div>
           {this.state.result ? this.renderResult() : this.renderTest()}
           <Baoquestion />
           <AnswerChoices />
           <BaoScore />
           <Score />
       </div>      
    );
}


export default App;

Score.js的内容

Content of Score.js

 import React, { Component } from 'react';
 import PropTypes from 'prop-types';
 import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';

 function Score(props) {

 return (
 <div>
 <CSSTransitionGroup 
  className="container result"
  transitionName="test"
  transitionEnterTimeout={500}
  transitionLeaveTimeout={300}>
 >
  <div>
    You prefer <strong>{props.testScore}</strong>!
  </div>
</CSSTransitionGroup>
</div>
);

 }

 Score.propTypes = {
 quizResult: PropTypes.string,
 };

 export default Score;

推荐答案

来自 react-transition-group文档:

即使仅呈现单个项目,也必须为CSSTransitionGroup的所有子项提供key属性.这就是React决定哪些孩子进入,离开或停留的方式.

You must provide the key attribute for all children of CSSTransitionGroup, even when only rendering a single item. This is how React will determine which children have entered, left, or stayed.

然后为您在过渡组中渲染的组件添加一个键,甚至是一个静态键:

Please then add a key, even a static one, for the component you render inside the transition group:

<CSSTransitionGroup 
 className="container result"
 transitionName="test"
 transitionEnterTimeout={500}
 transitionLeaveTimeout={300}>
>
  <div key="transition-group-content" >
    You prefer <strong>{props.testScore}</strong>!
  </div>
</CSSTransitionGroup>

这篇关于错误React.Children.only仅预期接收单个React元素的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆