Skip to content

Instantly share code, notes, and snippets.

@u88803494
Created November 27, 2019 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save u88803494/ca52af81f9d8c1b309be40c9d8294b4c to your computer and use it in GitHub Desktop.
Save u88803494/ca52af81f9d8c1b309be40c9d8294b4c to your computer and use it in GitHub Desktop.
只含改變的部分
import React, { Component } from 'react';
import './App.css';
import Nav from './nav';
import About from './about';
import Home from './home';
import Post from './post';
const removeHashTag = str => {
return str.slice(1);
}
const Route = ({ current, path, Comp }) => (current !== path ? null : <Comp />)
class App extends Component {
constructor(props) {
super(props)
this.state = {
tab: removeHashTag(window.location.hash) || 'home',
}
}
componentDidMount() {
window.addEventListener("hashchange", this.handleHashChange);
} // 在載入的時候新增監聽器
componentWillUnmount() {
window.removeEventListener(this.handleHashChange);
} // 結束之後要拿掉這個 listener
handleHashChange = () => {
this.setState({
tab: removeHashTag(window.location.hash),
})
}
render() {
const { tab } = this.state
return (
<div className="App" >
<Nav activeTab={tab} />
<div className="page">
<Route current={tab} path={'home'} Comp={Home} />
<Route current={tab} path={'post'} Comp={Post} />
<Route current={tab} path={'about'} Comp={About} />
</div>
</div>
);
}
}
export default App;
.nav {
position: fixed;
top: 0;
left: 0;
right: 0;
background: #bbbbbb;
opacity: 0.8;
z-index: 2;
}
.nav__list {
list-style: none;
padding: 0;
text-align: left;
margin-left: 20px;
}
.nav__list li {
display: inline-block;
margin-right: 16px;
background: rgba(255, 0, 0, 0.3);
padding: 10px;
transition: background 0.3s;
cursor: pointer;
}
.nav__list a {
text-decoration: none;
color: black;
}
.nav__list li:hover {
background: rgba(255, 0, 0, 0.5);
}
.nav__list .active {
background: rgba(255, 0, 0, 0.5);
}
import React, { Component } from 'react';
import './Nav.css';
class Item extends Component {
render() {
const { name, text, isActive } = this.props;
return (
<a href={'#' + name}>
<li className={isActive && 'active'}>
{text}
</li>
</a>
)
}
}
class Nav extends Component {
render() {
const { activeTab } = this.props;
return (
<nav className="nav" >
<ul className="nav__list">
<Item
isActive={activeTab === 'home' || ''}
name='home'
text='Home'
/>
<Item
isActive={activeTab === 'post' || ''}
name='post'
text='文章列表'
/>
<Item
isActive={activeTab === 'about' || ''}
name='about'
text='關於本站'
/>
</ul>
</nav>
);
}
}
export default Nav;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment