【问题标题】:How to render multiple components in react?如何在反应中渲染多个组件?
【发布时间】:2019-12-13 08:57:18
【问题描述】:

我正在尝试学习反应并在小范围内遇到问题。所以这是我的App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';

class App extends React.Component{
  render(){
    return <h1>Heyy</h1>;
  }
  render(){
    return <h1>Helo</h1>
  }
}

export default App;

它只渲染Helo。如果我有多个组件,比如说NavBarImageComp,在将它传递给ReactDOM.render 之前,我将如何在单个页面上呈现它?

据我了解,在进入index.js 之前,每个组件都会进入App,但是我将如何在应用程序中包含多个组件?

【问题讨论】:

    标签: html reactjs jsx


    【解决方案1】:

    Component 必须返回 JSX 或不返回任何 null。您需要从基于类的组件中渲染的所有内容都应该放在 render 方法中:

    class App extends Component{
        render(){
             return(
               <>
                   <h1>Title</h1>
                   <h2> Subtitle </h2>
                   <MyCustomComponent />
               </>
            )
        }
    }
    

    符号&lt;&gt; &lt;/&gt; 它只是&lt;React.Fragment /&gt; 的快捷方式,以避免返回相邻的JSX

    【讨论】:

    • 那么我所有的组件都进入一个渲染方法了吗?你能提供组件而不是html的例子吗?
    • 谢谢!这很有帮助!
    【解决方案2】:

    React 还允许你返回一个元素数组。

    class App extends Component{
      render(){
         return[          
               <h1>Title</h1>,
               <h2> Subtitle </h2>,
               <MyCustomComponent />
         ]
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 2017-02-18
      • 2022-01-08
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2019-09-15
      相关资源
      最近更新 更多