30_react_router基本使用

时间:2024-03-25 08:03:55

项目结构:

  30_react_router基本使用

import React from 'react'
import {render} from 'react-dom'
import {BrowserRouter} from 'react-router-dom'

import App from './components/app'

render(
    (
        <BrowserRouter>
            <App/>
        </BrowserRouter>
    ),
    document.getElementById('root')
)

index.jsx

import React, {Component} from 'react'
import {NavLink, Switch, Route, Redirect} from 'react-router-dom'

import About from '../views/about'
import Home from '../views/home'

export default class App extends Component {
    render() {
        return (
            <div>
                <div className='row'>
                    <div className='col-xs-8 col-xs-offset-2'>
                        <div className='page-header'>
                            <h2>React Router Demo</h2>
                        </div>
                    </div>
                </div>
                <div className='row'>
                    <div className='col-xs-2 col-xs-offset-2'>
                        <div className='list-group'>
                            <NavLink className='list-group-item' to='/about'>about</NavLink>
                            <NavLink className='list-group-item' to='/home'>home</NavLink>
                        </div>
                    </div>
                    <div className='col-xs-6'>
                        <div className='panel'>
                            <div className='panel-body'>
                                <Switch>
                                    <Route path='/about' component={About}/>
                                    <Route path='/home' component={Home}/>
                                    <Redirect to='/home'/>
                                </Switch>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

app.jsx

import React, {Component} from 'react'

export default class About extends Component {
    render() {
        return (
            <div>
                about route component
            </div>
        )
    }
}

about.jsx

import React, {Component} from 'react'

export default class Home extends Component {
    render() {
        return (
            <div>
                home route component
            </div>
        )
    }
}

home.jsx