如何将多个React类渲染到一个根节点中?

时间:2020-04-11 11:59:52

标签: reactjs

我正在使用React创建一个网站。我意识到在构建之后,它仅显示和组件。

这是我的App.js的样子:

class initialization

我想知道如何呈现所有其他类,以便在单击标题链接时(如在普通网站中一样)将它们显示为自己的页面

2 个答案:

答案 0 :(得分:0)

您可以使用链接创建指向这些页面的链接:

import { Link } from 'react-router-dom';
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/projects">Projects</Link>
...

我的方法是让NavBar组件具有所有Links,而AppRoutes组件具有所有这样的路由:

const App = () => {
    return (
        <BrowserRouter>
                <NavBar />
                <AppRoutes />
        </BrowserRouter>
    );
}

答案 1 :(得分:0)

我终于找到了解决方法:

import React, { Component } from 'react';
import './App.css';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import Home from './components/Home/Home';
import About from './components/About/About';
import Team from './components/Team/Team';
import Projects from './components/Projects/Projects';
import Contact from './components/Contact/Contact';
import Documents from './components/Documents/Documents';
import FAQ from './components/FAQ/FAQ';
import { HashRouter as Router, Route, Link, Switch, Redirect } from 'react-router-dom';

function App() {

      return (
        <Router>
            <div className="App">
              <Header />
              <Switch>
                <Route exact={true} path="/" component={Home} />
                <Route exact path="/about" component={About} />
                <Route exact path="/projects" component={Projects} />
                <Route exact path="/team" component={Team} />
                <Route exact path="/contact" component={Contact} />
                <Route exact path="/documents" component={Documents} />
              </Switch>
              <Footer />
            </div>
        </Router>
      );
    }

export default App;

我要做的是将路由嵌套在Route和Switch中,然后将导入更改为HashRouter,这就是组件未加载的原因。