昨天己經安裝了react-router-dom,在index.js頁面中導入 BrowserRouter,在App.js頁面中導入Route 和 Switch並完成了React Router path component設定,今天將繼續介紹創建一個簡單的 React 導航欄Navigation。
1.建立一個Navbar.js,導入{NavLink} react-router-dom
import{ NavLink } from 'react-router-dom';
2.在HTML中如要建立Navigation中的各頁面連結是用<a href="#home">home </a>
標籤,在React中建立頁面連結用< NavLink to =” ”>
,首頁一樣加上exact。
<NavLink exact to="/"> home </NavLink>
3.最後再把Navbar模組加到App.js中。
Navbar.js
import React from 'react';
import{ NavLink } from 'react-router-dom';
const Navbar = () => {
return (
<div>
<div className="header-2">
<div id="menu-bar" class="fas fa-bars"></div>
<nav className="navbar">
<NavLink exact to="/"> home </NavLink>
<NavLink to="/About US"> About US </NavLink>
<NavLink to="/product"> product </NavLink>
<NavLink to="/Services"> Services </NavLink>
<NavLink to="/contact"> contact </NavLink>
</nav>
<div className="icons">
<i class="fas fa-shopping-cart"></i>
<i class="fas fa-user-circle"></i>
<i class="fas fa-map-marker-alt"></i>
</div>
</div>
</div>
)
}
export default Navbar;
App.js
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Product from './Product';
import Services from './Services';
import Contact from './Contact';
import Error from './Error';
import Navbar from './Navbar';
const App = () => {
}
return (
<div>
<Navbar />
<Switch>
<Route exact path="/" component = {Home} />
<Route path="/about" component = {About} />
<Route path="/product" component = {Product} />
<Route path="/Services" component = {Services} />
<Route path="/contact" component = {Contact} />
<Route component = {Error} />
</Switch>
</div>
)
}
export default App;