react路由配置

前端之家收集整理的这篇文章主要介绍了react路由配置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

包含了LInk跳转以及js触发跳转并传参。

这是项目的目录结构,主要的代码都在src目录下,src下面新建一个containers文件夹放我们的一些组件,router文件夹是配置路由用的。

按照顺序来写:detail文件夹下的代码

import React from 'react'

class Detail extends React.Component {
    render() {
        return (
            <p>Detail,url参数:{this.props.params.id}</p>
        )
    }
}

export default Detail
home:
import React from 'react'
import { Link } from 'react-router'

class Home extends React.Component {
    render() {
        return (
            <div>
                <p>Home</p>
                <Link to="/list">to list</Link>
            </div>
        )
    }
}

export default Home
list:
import React from 'react'
import { hashHistory } from 'react-router'

class List extends React.Component {
    render() {
        const arr = [1,2,3]
        return (
            <ul>
                {arr.map((item,index) => {
                    return <li key={index} onClick={this.clickHandler.bind(this,item)}>js jump to {item}</li>
                })}
            </ul>
        )
    }
    clickHandler(value) {
        hashHistory.push('/detail/' + value)
    }
}

export default List
404yemian:
import React from 'react'

class NotFound extends React.Component {
    render() {
        return (
            <p>404 NotFound</p>
        )
    }
}

export default NotFound

在containers下面有一个app.jsx总入口文件

import React from 'react'

class App extends React.Component {
    render() {
        return (
            <div>{this.props.children}</div>
        )
    }
}

export default App
router文件夹下的:
import React from 'react'
import { Router,Route,IndexRoute } from 'react-router'

import App from '../containers/App'
import Home from '../containers/Home'
import List from '../containers/List'
import Detail from '../containers/Detail'
import NotFound from '../containers/NotFound'

class RouteMap extends React.Component {
    updateHandle() {
        console.log('每次router变化之后都会触发')
    }
    render() {
        return (
             <Router history={this.props.history} onUpdate={this.updateHandle.bind(this)}>
                <Route path='/' component={App}>
                    <IndexRoute component={Home}/>
                    <Route path='list' component={List}/>
                    <Route path='detail/:id' component={Detail}/>
                    <Route path="*" component={NotFound}/>
                </Route>
            </Router>
        )
    }
}

export default RouteMap
最终最外层的index.js:
import React from 'react'
import { render } from 'react-dom'
import { hashHistory } from 'react-router'

import RouteMap from './src/router/routeMap'

render(
    <RouteMap history={hashHistory}/>,document.getElementById('App')
)
使用的router版本是^2.8.1,如果下载的是4.0以上的版本,那么写法就和现在的几乎是完全不一样,他做了很大的改动,配置的时候注意router的版本号。

项目地址https://github.com/wineSu/myReact/tree/master/src/containers 原文链接:https://www.f2er.com/react/303282.html

猜你在找的React相关文章