首页 > 解决方案 > 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>
  );

PS。错误发生在返回的 ) 处。

标签: javascripthtmlcssreactjs

解决方案


您有此错误,因为您同时返回两个元素。您的两个 div 都需要包装在父元素中。

你可以使用React.Fragment来做到这一点。如文档中所述(https://reactjs.org/docs/react-api.html#reactfragment

React.Fragment 组件允许您在 render() 方法中返回多个元素,而无需创建额外的 DOM 元素

return(
<React.Fragment>
 <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 SpinSpeed!
        </button>
    </header>
  </div>
</React.Fragment>
);

推荐阅读