使用指南:
文件名:App.js,并复制到create-react-app 创建的项目的src/下,即可使用
import React from 'react'
import { BrowserRouter, Route, NavLink, Link } from 'react-router-dom'
const style = {
actived: { color: 'white',backgroundColor:'red' },
subActived:{ color: 'white',backgroundColor:'red' }
}
export default class App extends React.Component {
render() {
return (
<div>
<h1 style={style.xx}>使用react-router-dom</h1>
<BrowserRouter>
<NavLink to='/' style={{ color: 'blue' }} >home</NavLink>
----<NavLink activeStyle={style.actived} to='/about'>about</NavLink>
----<NavLink activeStyle={style.actived} to='/topics'>所有的主题</NavLink>
<Route path='/' component={Home} exact></Route>
<Route path='/about' component={About} exact></Route>
<Route path='/topics' component={Topics} exact></Route>
</BrowserRouter>
</div>
)
}
}
class Home extends React.Component {
render() {
return (<div>
<h1>This is home</h1>
</div>)
}
}
class About extends React.Component {
render() {
return (<div>
<h1>About me</h1>
</div>)
}
}
class Topics extends React.Component {
constructor(props){
super(props)
this.state={topics:[{id:9,title:'titile9'},{id:8,title:'titile8'}]}
}
render() {
return (
<div>
<h1>主题列表</h1>
<BrowserRouter>
<ul>
<li>
<NavLink activeStyle={style.subActived} to={`${this.props.match.url}/rendering`}>
使用 React 渲染
</NavLink>
</li>
<li>
<NavLink activeStyle={style.subActived} to={`${this.props.match.url}/components`}>
NavLink 组件
</NavLink>
</li>
<li>
<NavLink activeStyle={style.subActived} to={`${this.props.match.url}/props-v-state`}>
属性 v. 状态
</NavLink>
</li>
<li>
<NavLink activeStyle={style.subActived} to={`${this.props.match.url}/components12`}>
NavLink 组件
</NavLink>
</li>
{/* 以下是动态生成链接 */}
{this.state.topics.map(topic=>{
return (
<li>
<NavLink activeStyle={style.subActived} to={`${this.props.match.url}/${topic.id}`}>{topic.title}</NavLink>
</li>
)
})}
</ul>
<Route exact path={`${this.props.match.url}/rendering`} component={Topic} />
<Route path={`${this.props.match.url}/:topicId`} component={Topic}/>
<Route exact path={this.props.match.url} render={() => (
<h3>请选择一个主题</h3>
)} />
</BrowserRouter>
</div>
)
}
}
class Topic extends React.Component {
render() {
return (
<div>
<h3>显示主题</h3>
<h5>这是传递过来参数:{this.props.match.params.topicId}</h5>
</div>
)
}
}
网友评论