react-router使用教程
-
关于url中#的作用:
'#'代表网页中的一个位置。其右面的字符,就是该位置的标识符
改变#不触发网页重载
改变#会改变浏览器的访问历史
window.location.hash读取#值
window.onhashchange = func 监听hash改变
-
reat-router
github主页: https://github.com/ReactTrain...
官网教程: https://github.com/reactjs/re...官方教程)
-
react-router库中的 相关组件
-
下载相关插件:
npm install react-router@3 --save
-
编码
-
定义各个路由组件
-
About.js
import React from 'react' function About() { return <div>About组件内容</div> } export default About
-
Home.js
import React from 'react' function Home() { return <div>Home组件内容2</div> } export default Home
-
Repos.js
import React,{Component} from 'react' import {Link} from 'react-router'; export default class Repos extends Component { constructor(props){ super(props); this.state = { repos : [] } } componentDidMount(){ let repos = [ {name : 'facebook',repo : 'yarn'},{name : 'facebook',repo : 'react'},{name : 'google',repo : 'angular'},{name : 'antd',repo : 'antd'},]; this.setState({repos}); } render() { return ( <div> <h3>Repos 组件</h3> <ul> { this.state.repos.map((item,index) => { return <li key={index}><Link to={`/repos/${item.name}/${item.repo}`}>{item.repo}</Link></li> }) } </ul> {this.props.children} </div> ) } }
-
-
定义应用组件: App.js
import React from 'react'; import {Link} from 'react-router' class App extends React.Component{ render(){ return ( <div> <h2>Hello,React Router!</h2> <ul> <li><Link to="/about">about</Link></li> <li><Link to="/repos">repos</Link></li> </ul> {this.props.children} </div> ) } } export default App;
-
定义入口JS: index.js-->渲染组件
import React from 'react'; import ReactDOM from 'react-dom'; import {Router,Route,hashHistory,IndexRoute} from 'react-router'; import App from './components/App/App'; import About from './components/About/About'; import Repos from './components/Repos/Repos'; import Home from './components/Home/Home'; import Repo from './components/Repo/Repo'; ReactDOM.render( ( <Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={Home}></IndexRoute> <Router path="/about" component={About}></Router> <Router path="/repos" component={Repos}> <Route path="/repos/:name/:repo" component={Repo}></Route> </Router> </Route> </Router> ),document.getElementById('root') );
-
主页面: index.html
<style> .active { color: red; } </style> <div id='root'></div>
-
-
传递请求参数
-
repo.js: repos组件下的分路由组件
import React from 'react'; function Repo({params}) { return <p>用户名:{params.name},仓库名:{params.repo}</p> } export default Repo;
-
repos.js
import React,index) => { return <li key={index}><Link to={`/repos/${item.name}/${item.repo}`}>{item.repo}</Link></li> }) } </ul> {this.props.children} </div> ) } }
-