环境搭建
推荐使用npm搭建项目环境,如果网速过慢,可是使用cnpm进行项目的搭建(cnpm是淘宝的npm镜像,与npm有些差异,有些模块无法下载或无法正常使用)。
cnpm install -g create-react-appcreate-react-app my-appcd my-appnpm start复制代码
打开浏览器,输入http://localhost:3000可以看到系统默认生成的页面了。
注:node版本最好8.0版本以上
目录结构
路由配置
index.js
import React from 'react'import ReactDOM from 'react-dom'import './index.css'import { BrowserRouter } from 'react-router-dom'import Root from './router/Router'import * as serviceWorker from './serviceWorker'const mountNode = document.getElementById('root')ReactDOM.render(, mountNode)// If you want your app to work offline and load faster, you can change// unregister() to register() below. Note this comes with some pitfalls.// Learn more about service workers: http://bit.ly/CRA-PWAserviceWorker.unregister()复制代码
app.js
/* App 应用总容器*/import React, { Component } from 'react'class App extends Component { render() { return{this.props.children}}}export default App复制代码
Router.js
/* Root, Router 配置*/import React from 'react'import { Route, Switch, Redirect } from 'react-router-dom'import App from './../App'import Test from './../containers/Test'import Home from './../containers/Home'import Message from './../containers/Message'const Root = () => ()export default Root复制代码( )} /> {/*路由不正确时,默认跳回home页面*/} } />
containers中的三个文件
/* Home 主页*/import React, { Component } from 'react'import { Link } from 'react-router-dom'class Home extends Component { render() { return ({/*search,state可以自定义,获取方法:this.props.location.search,this.props.location.state*/} 点击跳转到路由参数search,state使用) }}export default Home/* Message 主页*/import React, { Component } from 'react'class Message extends Component { // constructor(props) { // super(props) // } render() { returnMessage{this.props.match.params.id}
}}export default Message/* Test 主页*/import React, { Component } from 'react'import { Link } from 'react-router-dom'class Test extends Component { // constructor(props) { // super(props) // } render() { return () }}export default Test复制代码search:{this.props.location.search}
state:{this.props.location.state.mold}
this.props.history.goBack()}>返回上一页message页面1this.props.history.push('/message/12')}> message页面2