history相关API的使用
history test
test1
(react-router4 相关 API详细网址:https://blog.csdn.net/qq_41846861/article/details/86688754)
组件
其他
路由组件: views/about.jsx
import React from 'react'
export default function About() {
return About组件内容
}
一级路由组件: views/home.jsx
import React from 'react'
import {Switch, Route, Redirect} from 'react-router-dom'
import MyNavLink from '../components/my-nav-link'
import News from './news'
import Message from './message'
export default function Home() {
return (
Home组件内容
-
News
-
Message
)
}
包装 NavLink 组件: components/my-nav-link.jsx
import React from 'react'
import {NavLink} from 'react-router-dom'
export default function MyNavLink(props) {
return
}
应用组件: components/app.jsx
import React from 'react'
import {Route, Switch, Redirect} from 'react-router-dom'
import MyNavLink from './my-nav-link'
import About from '../views/about'
import Home from '../views/home'
export default class App extends React.Component {
render() {
return (
React Router Demo
{/*导航路由链接*/}
About
Home
{/*可切换的路由组件*/}
)
}
}
自定义样式: index.css
.activeClass {
color: red !important;
}
入口 JS: index.js
import React from 'react'
import ReactDOM from 'react-dom'
import {BrowserRouter, HashRouter} from 'react-router-dom'
import App from './components/app'
import './index.css'
ReactDOM.render(
(
/*
*/
),
document.getElementById('root')
)
二级路由组件: views/news.jsx
import React from 'react'
export default class News extends React.Component {
state = {
newsArr: ['news001', 'news002', 'news003']
}
render () {
return (
{
this.state.newsArr.map((news, index) => - {news}
)
}
)
}
多种路由组件跳转方式
二级路由组件: views/message.jsx
import React from 'react'
import {Link, Route} from 'react-router-dom'
import MessageDetail from "./message-detail"
export default class Message extends React.Component {
state = {
messages: []
}
componentDidMount () {
// 模拟发送ajax请求
setTimeout(() => {
const data = [
{id: 1, title: 'Message001'},
{id: 3, title: 'Message003'},
{id: 6, title: 'Message006'},
]
this.setState({
messages: data
})
}, 1000)
}
ShowDetail = (id) => {
this.props.history.push(`/home/message/${id}`)
}
ShowDetail2 = (id) => {
this.props.history.replace(`/home/message/${id}`)
}
back = () => {
this.props.history.goBack()
}
forward = () => {
this.props.history.goForward()
}
render () {
const path = this.props.match.path
return (
{
this.state.messages.map((m, index) => {
return (
-
{m.title}
)
})
}
)
}
}
向路由组件传递参数数据
三级路由组件: views/message-detail.jsx
import React from 'react'
const messageDetails = [
{id: 1, title: 'Message001', content: '我爱你, 中国'},
{id: 3, title: 'Message003', content: '我爱你, 老婆'},
{id: 6, title: 'Message006', content: '我爱你, 孩子'},
]
export default function MessageDetail(props) {
const id = props.match.params.id
const md = messageDetails.find(md => md.id===id*1)
return (
- ID: {md.id}
- TITLE: {md.title}
- CONTENT: {md.content}
)
}
Router案例知识点总结:
1.Switch:路由转换设置,如图
2.Redirect 自动设置默认指定 如上图在未点击鼠标时 默认指定About
3.Route 两个变量
如何编写路由效果:
/
涉及时写
页面URL有#/
,
多页面切换,
自动跳转-指定页面优先显示
,
多了一个nameClass