React系列之--项目中React 路由搭建demo

                                  React系列之--项目中React 路由搭建demo

关于react-router网上有很多介绍,在这里必要唠叨,其中在项目中react-router和react-router-dom功能是一样的,引用一个就可以了。

1、react-router4.0以上的介绍。

    发现一篇文章写得不错,在这里也必要唠叨一次了。请阅:初探 React Router 4.0

2、搭建的环境

     a、使用create-react-app搭建

      b、版本如下:

{
  "name": "react-project-router",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-router-dom": "^4.3.1",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

3、文件目录结构

React系列之--项目中React 路由搭建demo_第1张图片


 5、index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import './index.css';
import Root from './router/Routes';
import registerServiceWorker from './registerServiceWorker';

const mountNode = document.getElementById('root');
ReactDOM.render(
    
        
    ,
    mountNode
);
registerServiceWorker();

6、App.js

/*
   App 应用总容器
*/
import React, { Component } from 'react';

class App extends Component {
    render() {
        return 
{this.props.children}
; } } export default App;

7、Router文件,路由配置

/*
   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 = () => (
   
( {/*路由不正确时,默认跳回home页面*/} } /> )} />
); export default Root;

8、相关组件代码

/*
   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; /* Test 主页 */ import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class Test extends Component { constructor (props) { super(props) } render() { return (

search:{this.props.location.search}

state:{this.props.location.state.mold}

this.props.history.goBack()}>返回上一页
this.props.history.push('/message/12')}>message页面
); } } export default Test; /* Message 主页 */ import React, { Component } from 'react'; class Message extends Component { constructor (props) { super(props) } render() { return (

Message{this.props.match.params.id}

); } } export default Message;
9、效果如下

       React系列之--项目中React 路由搭建demo_第2张图片


源码:https://github.com/qishuixian/react/tree/master/react-project-router

你可能感兴趣的:(react,react学习笔记)