react-router-dom里面封装的办法:
import React from "react";
import {Router,Route,BrowserRouter} from 'react-router-dom'
import {createBrowserHistory} from 'history'
let BrowserHistory = createBrowserHistory();
class AA extends React.Component{
render() {
return (
<div>
aa
</div>
);
}
}
class BB extends React.Component{
render() {
return (
<div>
bb
</div>
);
}
}
function App() {
return (
<div className="App">
<BrowserRouter basename={'/users'}>
<header className="App-header" >
<div>header</div>
<Route path='/aa' component={AA}/>
<Route path='/bb' component={BB}/>
</header>
</BrowserRouter>
</div>
);
}
export default App
pathname改变,使用window.history.route监听事件,设置pathname,使用window.history.pushState改变url地址;
使用上下文去传递pathname ,选择渲染子组件
import React from 'react';
import './App.css';
import PropTypes from 'prop-types'
class Router extends React.Component{
constructor(props) {
super(props);
this.state = {
url: window.location.pathname
}
this.history = window.history
this.history.route = (name) => {
this.setState({
url: `/${name}`
})
window.history.pushState(null,null,name)
}
}
render() {
return (
<>
{this.props.children}
</>
);
}
static childContextTypes = {
url: PropTypes.string,
history: PropTypes.object
}
getChildContext () {
return {
url: this.state.url,
history: this.history
}
}
componentDidMount() {
// window.onhashchange = () => {
// this.setState({
// hash: this.getHash()
// })
// }
window.onpopstate = (a) => {
console.log(a)
}
}
}
class Route extends React.Component{
static contextTypes = {
url: PropTypes.string,
history: PropTypes.object
}
render() {
const {
component,
path
} = this.props
const {
url
} = this.context
return (
<>
{url === path && React.createElement(component,null,null)}
</>
);
}
componentDidMount() {
}
}
const AA = () => <div>aa</div>
const BB = () => <div>bb</div>
function App() {
return (
<div className="App">
<Router >
<header className="App-header">
<div>header</div>
<Route path='/aa' component={AA}/>
<Route path='/bb' component={BB}/>
</header>
</Router>
</div>
);
}
export default App;