如何在React应用程序的新页面中渲染组件

问题描述 投票:0回答:1

我随身携带了所有组件,并且链接也有效。下面是App.jsx的代码

import { useState } from 'react';
import Home from "./Components/Home";
import Secondquestion from "./Components/Secondquestion";
import Nextquestion from './Components/Nextquestion';
import {Link,Route, Routes } from 'react-router-dom'; 
import './App.css';

function App() {  
  return (
    <div>
      <ul>
        <li>
          <Link to="/home">Home</Link>
        </li>
        <li>
          <Link to="/next">Nextquestion</Link>
        </li>
        <li>
          <Link to="/second">Secondquestion</Link>
        </li>
      </ul>
      <Routes>
        <Route path="/home" element={<Home></Home>}></Route>
        <Route path="/next" element={<Nextquestion/>}></Route>
        <Route path="/second" element={<Secondquestion/>}></Route>
      </Routes>
    </div>
  );
}

export default App

main.jsx 代码

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import { BrowserRouter } from 'react-router-dom'
import './index.css'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <BrowserRouter>
    <App />
    </BrowserRouter>
  </StrictMode>,
)

链接有效,但在同一页面中呈现。但我想让它们进入一个新页面。如何做到这一点。

javascript html reactjs react-hooks react-router
1个回答
0
投票

您已将路线放置在列表下方,因此它会显示在同一页面上。如果您想将它们单独呈现为独立页面,您可以将代码修改为:

import { useState } from 'react';
import Home from "./Components/Home";
import Secondquestion from "./Components/Secondquestion";
import Nextquestion from './Components/Nextquestion';
import {Link,Route, Routes } from 'react-router-dom'; 
import './App.css';

function App() {  
  return (
    <div>
      <Routes>
        <Route path="/home" element={<Home></Home>}></Route>
        <Route path="/next" element={<Nextquestion/>}></Route>
        <Route path="/second" element={<Secondquestion/>}></Route>
      </Routes>
    </div>
  );
}

export default App

转到页面的选项将不可用,您必须通过地址栏中的路线直接访问

© www.soinside.com 2019 - 2024. All rights reserved.