安装依赖导入
// cnpm install react-router-dom -S // 或 // yarn add react-router-dom // index.js import React from 'react' import ReactDOM from 'react-dom' import App from "@/App" ReactDOM.render(<div> <App></App> </div>, document.getElementById('app'))
App.jsx
// App.jsx import React from "react" // HashRouter 表示一个路由的根容器,将来所有的路由相关的东西,都要包裹在 HashRouter 里,而且,一个网站中只使用一次 // Route 表示一个路由规则,在 Route 上有2个比较重要的属性, path 和 component // Link 表示一个路由的链接,好比 vue 中的 <router-link to=""></router-link> import { HashRouter, Route, Link, Redirect } from 'react-router-dom' // 使用 antd UI import { DatePicker } from 'antd' import Home from "@/conpenents/route/Home" import Movie from "@/conpenents/route/Movie" import About from "@/conpenents/route/About" class App extends React.Component { constructor(props) { super(props) this.state = { msg: '这是 BindThis组件中的 msg 消息' } } render() { // 启用路由 // HashRouter中,只能有唯一的根元素 // 一个网站中,只需要使用唯一的一次 <HashRouter> return <HashRouter> <div> <h1>这是 App 根组件 </h1> <DatePicker /> <hr/> <Redirect to="/home" /> <Link to="/home">首页</Link> <Link to="/movie/top250/102">电影</Link> <Link to="/about">关于</Link> <hr/> {/* 路由规则 */} <Route path="/home" component={ Home }></Route> {/* 路由参数匹配 */} {/* 获取路由参数:this.props.match.params */} <Route path="/movie/:type/:id" component={ Movie } exact ></Route> <Route path="/about" component={ About }></Route> {this.props.children} </div> </HashRouter> } } export default App
Home.jsx
// Home.jsx import React from "react" class Home extends React.Component { constructor(props) { super(props) this.state = { msg: '这是 Home 组件' } } render() { return <div> <h1>{ this.state.msg }</h1> </div> } } export default Home
Movie.jsx
// Movie.jsx import React from "react" class Movie extends React.Component { constructor(props) { super(props) this.state = { // 方便获取路由参数 routeParams: props.match.params, msg: '这是 Movie 组件' } } render() { console.log(this) console.log(this.props.match.params) return <div> <h1>{ this.state.msg }</h1> <p>{ this.state.routeParams.type } - { this.state.routeParams.id }</p> </div> } } export default Movie
About.jsx
// About.jsx import React from "react" class About extends React.Component { constructor(props) { super(props) this.state = { msg: '这是 About 组件' } } render() { return <div> <h1>{ this.state.msg }</h1> </div> } } export default About
注意:按需导入antd
,需要配置.babelrc
:按需加载