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

左心房为你撑大大i 提交于 2021-02-07 18:06:59

问题


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.only expected to receive a single React element child'.

What exactly does this mean?

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;

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;

回答1:


From react-transition-group documentation:

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>



回答2:


<CSSTransitionGroup 
 className="container result"
 transitionName="test"
 transitionEnterTimeout={500}
 transitionLeaveTimeout={300}>
>                            ^ ** Must be a typo here **
^ ** Remove this '>' typo solve my problem **

The root cause of this error 'Error React.Children.only expected to receive a single React element child' is that there are two '>' in the ending of the JSX code. Remove one of the '>' solved this issue.



来源:https://stackoverflow.com/questions/44237033/error-react-children-only-expected-to-receive-a-single-react-element-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!