上一章 Day 25 - React Fetch 向後端API請求資料(2)
React 導頁與控制使用 react-router-dom
安裝的話只要按CTRL + ` 在Terminal輸入
npm install react-router-dom
React-router-dom 通常有兩種使用方式
HashRouter:
通過Hash值來對路由做控制, 使用上會發現Url多了一個#
例如: localhost:3000/#/members
但通常我們不需要這個#, 看起來也不直覺
BrowerRouter:
官網推薦使用BrowserRouter, 它使用History API (pushState, replaceState, popState)
HTML 5 的 History API 能夠在不刷新頁面的情況下更改URL的網址
首先導入Router與其他Component
App.js
import React, { Component } from 'react';
import './App.css';
import {
BrowserRouter,
Route,
Switch
} from 'react-router-dom';
import Home from './Home';
import Member from './Member';
import Vendor from './Vendor';
import Certificate from './Certificate';
class App extends Component {
render() {
return (
<BrowserRouter>
<Switch>
<Route path="/" component={Home} exact={true}></Route>
<Route path="/members" component={Member} exact={true}></Route>
<Route path="/certificates" component={Certificate} exact={true}></Route>
<Route path="/vendors" component={Vendor} exact={true}></Route>
</Switch>
</BrowserRouter>
);
}
}
export default App;
新增我們的首頁
Home.js
import React, { Component } from 'react';
import './App.css';
import 'bootstrap/dist/css/bootstrap.css';
import MyNavbar from './MyNavbar';
class Home extends Component {
render() {
return (
<div>
<MyNavbar />
</div>
);
}
}
export default Home;
修改導覽列
MyNavbar.js
import React, { Component } from 'react';
import {
Collapse,
Nav,
Navbar,
NavbarBrand,
NavbarToggler,
NavItem,
NavLink
} from 'reactstrap';
import {
BrowserRouter,
Route,
Switch,
Link
} from 'react-router-dom';
import logo from './logo.svg';
class MyNavbar extends Component {
constructor(props) {
super(props);
this.state = {
collapse: true
};
this.toogleNavbar = this.toogleNavbar.bind(this);
}
toogleNavbar() {
this.setState({
collapse: !this.state.collapse
});
}
render() {
return (
<Navbar color="dark" dark>
<NavbarBrand href="/" className="mr-auto">
<img
alt=""
src={logo}
width="30"
height="30"
className="d-inline-block align-top"
/>
{' Aiden'}
</NavbarBrand>
<NavbarToggler onClick={this.toogleNavbar} className="mr-2"/>
<Collapse isOpen={!this.state.collapse} navbar>
<Nav className="ml-auto" navbar>
<BrowserRouter>
<NavItem>
<NavLink href="/">首頁</NavLink>
</NavItem>
<NavItem>
<NavLink href="/members">會員中心</NavLink>
</NavItem>
<NavItem>
<NavLink href="/certificates">證照資訊</NavLink>
</NavItem>
<NavItem>
<NavLink href="/vendors">協辦單位</NavLink>
</NavItem>
<NavItem>
<NavLink href="https://ithelp.ithome.com.tw/users/20119510/articles">關於我</NavLink>
</NavItem>
<NavItem>
<NavLink href="https://github.com/AidenYang12345">GitHub</NavLink>
</NavItem>
</BrowserRouter>
</Nav>
</Collapse>
</Navbar >
);
}
}
export default MyNavbar;
啟動專案可以在Navbar看是不是能順利切換頁面
下一章教大家做首頁的動態橫幅廣告
Day 27 - React And BootStrap 動態橫幅廣告 Carousel