Installation depends
cnpm install react-router-dom -S // 或 yarn add react-router-dom
Importing
// 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 Import React from "REACT" // HashRouter represents a root container routes, the future of all things related to routing, to be wrapped in HashRouter years, and that a site is used only once // Route represent a route rules on route 2 has a relatively important attributes, path and Component // link represents a linking route, like <router-link to = "" > vue in </ Router-link> Import {HashRouter, the route, Link, from the Redirect} 'REACT-Router-DOM' // use the UI antd Import {from} the DatePicker 'antd' Import from Home "@ / conpenents / route / Home" Import from Movie "@ / conpenents / route / Movie" Import from the About "@ / conpenents / route / the About" class the extends React App.Component { constructor(props) { super(props)this = .STATE { msg: 'This is the message msg BindThis components' } } the render () { // Enable Routing // HashRouter in only have one unique root element // a site, one only need to use a unique <HashRouter> return <HashRouter> <div> <h1> this is the App root component </ h1> <DatePicker /> <HR /> <Redirect to = "/ Home" /> <Link to = "/ Home"> Home </ Link> & nbsp; <Link to = "/ movie / TOP250 / 102"> film </ Link> & nbsp; <Link to = "/ About"> about </ Link> <HR /> { / * Routing rule * / } <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 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 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 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
Note: Import Demand antd
, you need to configure .babelrc
: demand loading