我是react初学者,我使用create-react-app创建了一个react项目。当我在项目中添加react-router-dom时,在index.js中添加
<BrowserRouter>
,在Header.js中渲染我的菜单,但是渲染的页面不是预期的,因为我发现菜单位于页面底部,当我单击菜单时,页面主体位于菜单上方。我的代码在这里,你能帮我吗?
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter} from 'react-router-dom';
ReactDOM.render(
<BrowserRouter >
<App />
</BrowserRouter >,
document.getElementById('root')
);
//App.js
import styles from "./App.module.scss"
import ErrorBoundary from "./components/error-boundary/ErrorBoundary";
import Header from "./components/common/Header";
import {Route, Routes} from "react-router-dom";
import {useEffect, useState} from "react";
function About() {
return (
<div>about me.</div>
);
}
function Clock() {
const [tick, setTick] = useState('');
useEffect(() => {
let timerID = setInterval(() => {
let now = new Date();
setTick(now.toLocaleTimeString());
}, 1000);
return () => clearInterval(timerID);
}, [tick])
return (
<div>{tick}</div>
);
}
function Home() {
return (
<div>my home.</div>
);
}
function App() {
const navs = [
{id: 1, name: 'Home', path: '/', element: <Home/>},
{id: 2, name: 'About', path: '/about', element: <About/>},
{id: 3, name: 'Clock', path: '/clock', element: <Clock/>},
];
return (
<>
<Routes>
{
navs.map((nav) => {
return (
<Route key={nav.id} path={nav.path} element={nav.element}/>
);
})
}
</Routes>
<div className={styles.container}>
<ErrorBoundary>
<Header navs={navs}/>
</ErrorBoundary>
</div>
</>
);
}
export default App;
//Header.js
import {Link} from "react-router-dom";
import styles from './Header.module.scss';
import React, {Component} from 'react';
class Header extends Component {
render() {
return (
<>
<ul className={styles.menus}>
{
this.props.navs.map((nav) => {
return (
<li key={nav.id} className={styles.menu}>
<Link to={nav.path}>{nav.name}</Link>
</li>
);
})
}
</ul>
</>
);
}
}
export default Header;
只需将
Header
JSX 放在 Routes
上方即可。当 Route
组件的路径与当前 URL 匹配时,就会渲染该组件。
UI 层次结构应该是:
function App() {
const navs = [
{id: 1, name: 'Home', path: '/', element: <Home/>},
{id: 2, name: 'About', path: '/about', element: <About/>},
{id: 3, name: 'Clock', path: '/clock', element: <Clock/>},
];
return (
<>
<div className={styles.container}>
<ErrorBoundary>
<Header navs={navs}/>
</ErrorBoundary>
</div>
<Routes>
{
navs.map((nav) => {
return (
<Route key={nav.id} path={nav.path} element={nav.element}/>
);
})
}
</Routes>
</>
);
}
如果我想实现一个megamenu,我如何通过修改json等来调整上面的代码?谢谢