React学习demo
安装依赖导入
// 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(, document.getElementById('app'))
App.jsx
// App.jsx import React from "react" // HashRouter 表示一个路由的根容器,将来所有的路由相关的东西,都要包裹在 HashRouter 里,而且,一个网站中只使用一次 // Route 表示一个路由规则,在 Route 上有2个比较重要的属性, path 和 component // Link 表示一个路由的链接,好比 vue 中的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中,只能有唯一的根元素 // 一个网站中,只需要使用唯一的一次 return } } export default App 这是 App 根组件
首页 电影 关于
{/* 路由规则 */}{/* 路由参数匹配 */} {/* 获取路由参数:this.props.match.params */} {this.props.children}
Home.jsx
// Home.jsx import React from "react" class Home extends React.Component { constructor(props) { super(props) this.state = { msg: '这是 Home 组件' } } render() { return} } export default Home{ this.state.msg }
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} } export default Movie{ this.state.msg }
{ this.state.routeParams.type } - { this.state.routeParams.id }
About.jsx
// About.jsx import React from "react" class About extends React.Component { constructor(props) { super(props) this.state = { msg: '这是 About 组件' } } render() { return} } export default About{ this.state.msg }
注意:按需导入antd,需要配置.babelrc:按需加载