添加第二个 <div> 时,React JSX 表达式必须有父元素错误

当我尝试添加另一个反应时返回错误JSX Expressions must have one parent element。我不明白为什么这是因为它有一个父元素。


  return (

<div className="loginButton">

    <header className="loginButton">

        <button className='discordLogin' id='login'

            href="link-here"></button>

    </header>

</div>

<div className="App">

    <header className="App-header">

        <img key={speed} src={logo} style={animationStyle} className="App-logo-circle" id='spinnerLogo'

            alt="Spinning logo" />

        <p>Hello, and welcome to the begining of the Swiss Plus Website. <strong>We hope you enjoy your stay</strong>

        </p>

        <button className='App-button' id='fastLogoButton' onClick={faster}>Increase Spin Speed!</button>

        <button className='App-button' id='slowLogoButton' onClick={slower}>Decrease Spin Speed!</button>

    </header>

</div>

  );

附言。错误发生在返回的 ) 处。


森栏
浏览 72回答 3
3回答

牧羊人nacy

您出现此错误是因为您同时返回两个元素。您的两个 div 都需要包装在父元素中。您可以使用React.Fragment来执行此操作。React.Fragment 组件允许您在 render() 方法中返回多个元素,而无需创建额外的 DOM 元素

冉冉说

return(<React.Fragment>&nbsp;<div className="loginButton">&nbsp; &nbsp; <header className="loginButton">&nbsp; &nbsp; &nbsp; &nbsp; <button className='discordLogin' id='login'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; href="link-here"></button>&nbsp; &nbsp; </header>&nbsp;</div>&nbsp;<div className="App">&nbsp; &nbsp; <header className="App-header">&nbsp; &nbsp; &nbsp; &nbsp; <img key={speed} src={logo} style={animationStyle} className="App-logo-circle"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id='spinnerLogo'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alt="Spinning logo"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; <p>Hello, and welcome to the begining of the Swiss Plus Website. <strong>We hope&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; you enjoy your stay</strong>&nbsp; &nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; &nbsp; &nbsp; <button className='App-button' id='fastLogoButton' onClick={faster}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Increase Spin Speed!&nbsp; &nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; &nbsp; &nbsp; <button className='App-button' id='slowLogoButton' onClick={slower}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Decrease SpinSpeed!&nbsp; &nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; </header>&nbsp; </div></React.Fragment>);

慕码人8056858

React 组件要求您仅返回一个元素。React 中的一个常见模式是组件返回多个元素。片段允许您对子级列表进行分组,而无需向 DOM 添加额外的节点。  return (    <React.Fragment>      <ChildA />      <ChildB />      <ChildC />    </React.Fragment>  );通常这些元素被包装在例如 div 内。在大多数情况下,包装器 div 是“不相关的”,只是因为 React 组件要求您仅返回一个元素而添加。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5