在更改代码之前,我可以显示HomeScreen和LoginScreen
import React, { useState } from 'react'
import { Container } from 'react-bootstrap'
import Header from './components/header/Header'
import Sidebar from './components/sidebar/Sidebar'
import HomeScreen from './screens/homeScreen/HomeScreen'
import './_app.scss'
const App = () => {
const [sidebar, toggleSidebar] = useState(false)
const handleToggleSidebar = () => toggleSidebar(value => !value)
return (
<>
<Header handleToggleSidebar={handleToggleSidebar} />
<div className="app__container">
<Sidebar
sidebar={sidebar}
handleToggleSidebar={handleToggleSidebar}
/>
<Container fluid className="app__main">
<HomeScreen />
</Container>
</div>
</>
)
}
export default App
这是工作在此处输入图像描述
当我将代码更改为Layout 时
import React, { useState } from 'react'
import { Container } from 'react-bootstrap'
import Header from './components/header/Header'
import Sidebar from './components/sidebar/Sidebar'
import HomeScreen from './screens/homeScreen/HomeScreen'
import LoginScreen from './screens/loginScreen/LoginScreen'
import { Navigate, Route, Routes } from 'react-router-dom'
import './_app.scss'
const Layout = ({ children }) => {
const [sidebar, toggleSidebar] = useState(false)
const handleToggleSidebar = () => toggleSidebar(value => !value)
return (
<>
<Header handleToggleSidebar={handleToggleSidebar} />
<div className='app__container'>
<Sidebar
sidebar={sidebar}
handleToggleSidebar={handleToggleSidebar}
/>
<Container fluid className='app__main '>
{children}
</Container>
</div>
</>
)
}
const App = () => {
return (
<Routes>
<Route path='/' exact>
<Layout>
<HomeScreen />
</Layout>
</Route>
<Route path='/auth'>
<LoginScreen />
</Route>
<Route path='/search'>
<Layout>
<h1>asfaasfas</h1>
</Layout>
</Route>
<Route>
<Navigate to="/" />
</Route>
</Routes>
)
}
export default App
它没有任何错误。在此处输入图像描述
但什么也没显示。
在此处输入图像描述
在React Router V6中,我们使用element
道具将组件渲染为Route
。这个来自类似帖子的回答给出了一个很好的解释。
您还需要将应用程序包装在BrowserRouter
中。假设你所有的路线都使用相同的布局,我建议你的应用程序如下:
const App = () => {
<BrowserRouter>
<Layout>
<Routes>
<Routes path='/' element={<HomeScreen />} />
...
</Routes>
</Layout>
</BrowserRouter>
}