react-router-dom示例讲解(8)侧边栏

在react-router-dom的官方示例中,侧边栏是非常容易实现的一个示例,奇实现的核心就是展示两组Routes。

本示例的效果图如下:
这里写图片描述

相关的核心代码:

import React, {Component} from 'react';
import {
    BrowserRouter as Router,
    Route,
    Link,
    Switch,
    Redirect
} from 'react-router-dom';

const routes = [
    { path: '/',
        exact: true,
        sidebar: () => <div>home!</div>,
        main: () => <h2>Home</h2>
    },
    { path: '/bubblegum',
        sidebar: () => <div>bubblegum!</div>,
        main: () => <h2>Bubblegum</h2>
    },
    { path: '/shoelaces',
        sidebar: () => <div>shoelaces!</div>,
        main: () => <h2>Shoelaces</h2>
    }
]


class App extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <Router>
                <div style={{display:'flex'}}>
                    <div style={{width: '200px',backgroundColor: '#cccccc'}}>
                        <ul>
                            <li><Link to='/'>Home</Link></li>
                            <li><Link to='/bubblegum'>Bubblegum</Link></li>
                            <li><Link to='/shoelaces'>Shoelaces</Link></li>
                        </ul>
                        {
                            routes.map((item,index)=>{
                                return (
                                    <Route exact={item.exact} key={index} path={item.path} component={item.sidebar}/>
                                )
                            })
                        }
                    </div>
                    <div style={{flex: 1}}>
                        {
                            routes.map((item,index)=>{
                                return (
                                    <Route exact={item.exact} key={index} path={item.path} component={item.main}/>
                                )
                            })
                        }
                    </div>
                </div>
            </Router>
        );
    }
}


export default App;

总体的实现思路:
是比较简单的路由方式,一个Link组件对应两个Route组件,一个在侧边栏区域,一个在右边的主视图区域。

Route的展示是通过对routes数组进行两次map遍历得到的!

本示例的github地址:https://github.com/liwudi/react-router-dom8.git

下一篇:react-router-dom示例讲解(9)模糊匹配

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值