App.js:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import './App.css';
//定义组件的三种方式
// 1
class Home extends Component{
render(){
return (
<div>这里是主页</div>
);
}
}
// 路由嵌套(和路由变量)可以让多个路由对应一个组件
class News2 extends Component{
render(){
console.log(this.props.match.params.gxx)
return (
<Router>
<div>
<Link to={this.props.match.url+'/run'}>跑步</Link>
<Link to={this.props.match.url+'/swim'}>游泳</Link>
<Link to={this.props.match.url+'/photo'}>照相</Link>
<Route path={this.props.match.url+'/:name'} component={News2} />
</div>
</Router>
)
}
}
class News extends Component{
render(){
/*可通过this.props.match.url获取父级的路由地址*/
console.log(this.props.match.url); /*/News*/
return (
<Router>
<div>
{ /*<Link to='/News/run'>跑步</Link>
<Link to='/News/swim'>游泳</Link>
<Link to='/News/photo'>照相</Link>*/
/*可改写为*/}
{/*<Link to={this.props.match.url+'/run'}>跑步</Link>
<Link to={this.props.match.url+'/swim'}>游泳</Link>
<Link to={this.props.match.url+'/photo'}>照相</Link>
<Route path='/News/:gxx' component={Sport}/>*/}
{/*路由循环嵌套*/}
<Link to={this.props.match.url+'/run'}>跑步</Link>
<Link to={this.props.match.url+'/swim'}>游泳</Link>
<Link to={this.props.match.url+'/photo'}>照相</Link>
<Route path='/News/:gxx' component={News2}/>
</div>
</Router>
)
}
}
class Sport extends Component{
/*path='/News/:gxx' 这里的参数可以在后面的Sport组件中通过this.props.match.params.gxx获取*/
/*点击对应子路由获得参数run,swim,photo*/
render(){
return (
<div>这是一项运动</div>
)
}
}
//3 普通函数(中获取路由相关信息)
const About = function(data){
console.log(data.match.url)/*/About*/
return (
<div>这里是关于信息</div>
)
}
class App extends Component {
render() {
return (
/*路由要用Router标签包起来*/
<Router>
{/*要有一个根元素*/}
<div>
{/*to后为地址相对于当前地址而言*/}
<Link to='/'>首页</Link>
<Link to='/News'>新闻</Link>
<Link to='/About'>关于</Link>
{/*对应内容放在Route中 path为对应路径 component为对应组件 exact为严格匹配,只匹配路径为'/'的元素*/}
<Route exact path='/' component={Home} />
<Route path='/News' component={News} />
<Route path='/About' component={About} />
</div>
</Router>
);
}
}
export default App;