溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

React中配置子路由的實(shí)現(xiàn)方法

發(fā)布時(shí)間:2021-06-04 09:28:31 來(lái)源:億速云 閱讀:420 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)React中配置子路由的實(shí)現(xiàn)方法,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

1、組件First.js下有子組件:

import Admin from './Admin'
import FormCom from './FormCom'
import One from './One'
import ButtonCom from './ButtonCom'
import MenuCom from './MenuCom'
import StepsCom from './StepsCom'
import TabsCom from './TabsCom'
import TableCom from './TableCom'
import MessageCom from './MessageCom'
import NotificationCom from './NotificationCom'
import ProgressCom from './ProgressCom'
import SpinCom from './SpinCom'
import BadgeCom from './BadgeCom'

First.js完整代碼如下:

import React from 'react'
import { Layout, Menu } from 'antd';
import { UserOutlined, LaptopOutlined, NotificationOutlined } from '@ant-design/icons';
import { HashRouter, Route, Link } from 'react-router-dom'
import Admin from './Admin'
import FormCom from './FormCom'
import One from './One'
import ButtonCom from './ButtonCom'
import MenuCom from './MenuCom'
import StepsCom from './StepsCom'
import TabsCom from './TabsCom'
import TableCom from './TableCom'
import MessageCom from './MessageCom'
import NotificationCom from './NotificationCom'
import ProgressCom from './ProgressCom'
import SpinCom from './SpinCom'
import BadgeCom from './BadgeCom'
const { SubMenu } = Menu;
const { Header, Content, Sider } = Layout;

export default class First extends React.Component {
    constructor() {
        super();
    }

    //只展開(kāi)當(dāng)前父級(jí)菜單 begin
    rootSubmenuKeys = ['sub1', 'sub2', 'sub3'];

    state = {
        openKeys: ['sub1'],
    };

    onOpenChange = openKeys => {
        const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
        if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
            this.setState({ openKeys });
        } else {
            this.setState({
                openKeys: latestOpenKey ? [latestOpenKey] : [],
            });
        }
    };
    //只展開(kāi)當(dāng)前父級(jí)菜單 end

    render() {
        return (<div>
            <Layout>
                <HashRouter>
                    <Header className="header" style={{ position: 'fixed', zIndex: 1, width: '100%', paddingLeft: '20px'}}>
                        <div className="logo" style={{fontSize: '32px', color: '#ffffff', fontWeight: 'bold'}}>React App</div>
                        <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['1']}>
                            {/*<Menu.Item key="1">nav 1</Menu.Item>
                            <Menu.Item key="2">nav 2</Menu.Item>
                            <Menu.Item key="3">nav 3</Menu.Item>*/}
                        </Menu>
                    </Header>
                    <Layout>
                        <Sider width={200} className="site-layout-background" style={{
                            overflow: 'auto',
                            height: '100vh',
                            position: 'fixed',
                            left: 0,
                        }}>
                            <Menu
                                theme="dark"
                                mode="inline"
                                defaultSelectedKeys={['2']}
                                defaultOpenKeys={['sub1']}
                                style={{ height: '100%', paddingTop: '60px', borderRight: 0 }}
                                onOpenChange={this.onOpenChange}
                                openKeys={this.state.openKeys}
                            >
                                <SubMenu key="sub1" icon={<UserOutlined />} title="subnav 1">
                                    <Menu.Item key="1"><Link to={`${this.props.match.path}/admin`}>admin</Link></Menu.Item>
                                    <Menu.Item key="2"><Link to={`${this.props.match.path}/form`}>form</Link></Menu.Item>
                                    <Menu.Item key="3"><Link to={`${this.props.match.path}/one`}>One</Link></Menu.Item>
                                    <Menu.Item key="4"><Link to={`${this.props.match.path}/menu`}>Menu</Link></Menu.Item>
                                </SubMenu>
                                <SubMenu key="sub2" icon={<LaptopOutlined />} title="subnav 2">
                                    <Menu.Item key="5"><Link to={`${this.props.match.path}/step`}>Step</Link></Menu.Item>
                                    <Menu.Item key="6"><Link to={`${this.props.match.path}/tabs`}>Tabs</Link></Menu.Item>
                                    <Menu.Item key="7"><Link to={`${this.props.match.path}/table`}>Table</Link></Menu.Item>
                                    <Menu.Item key="8"><Link to={`${this.props.match.path}/message`}>Message</Link></Menu.Item>
                                </SubMenu>
                                <SubMenu key="sub3" icon={<NotificationOutlined />} title="subnav 3">
                                    <Menu.Item key="9"><Link to={`${this.props.match.path}/notification`}>Notification</Link></Menu.Item>
                                    <Menu.Item key="10"><Link to={`${this.props.match.path}/progress`}>ProgressCom</Link></Menu.Item>
                                    <Menu.Item key="11"><Link to={`${this.props.match.path}/spin`}>Spin</Link></Menu.Item>
                                    <Menu.Item key="12"><Link to={`${this.props.match.path}/badge`}>Badge</Link></Menu.Item>
                                    <Menu.Item key="13"><Link to={`${this.props.match.path}/button`}>Button</Link></Menu.Item>
                                </SubMenu>
                            </Menu>
                        </Sider>
                        <Layout style={{ padding: '84px 20px 20px', marginLeft: 200}}>
                            <Content
                                className="site-layout-background"
                                style={{
                                    padding: 24,
                                    margin: 0
                                }}
                            >
                                <Route path={`${this.props.match.path}/admin`} exact component={Admin}></Route>
                                <Route path={`${this.props.match.path}/form`} component={FormCom}></Route>
                                <Route path={`${this.props.match.path}/one`} component={One}></Route>
                                <Route path={`${this.props.match.path}/menu`} component={MenuCom}></Route>
                                <Route path={`${this.props.match.path}/step`} component={StepsCom}></Route>
                                <Route path={`${this.props.match.path}/tabs`} component={TabsCom}></Route>
                                <Route path={`${this.props.match.path}/table`} component={TableCom}></Route>
                                <Route path={`${this.props.match.path}/message`} component={MessageCom}></Route>
                                <Route path={`${this.props.match.path}/notification`} component={NotificationCom}></Route>
                                <Route path={`${this.props.match.path}/progress`} component={ProgressCom}></Route>
                                <Route path={`${this.props.match.path}/spin`} component={SpinCom}></Route>
                                <Route path={`${this.props.match.path}/badge`} component={BadgeCom}></Route>
                                <Route path={`${this.props.match.path}/button`} component={ButtonCom}></Route>
                            </Content>
                        </Layout>
                    </Layout>
                </HashRouter>
            </Layout>
        </div>)
    }
}

其中

${this.props.match.path}

是關(guān)鍵。

2、假設(shè)還有一個(gè)登錄組件Login.js,代碼如下:

import React from 'react'
import { Button } from 'antd';

export default class Login extends React.Component {
    constructor() {
        super();
    }

    redirectHandle = () => {
        console.log("aaa");
        this.props.history.push("/home");
    }

    render() {
        return (<Button type="primary" onClick={()=>this.redirectHandle()}>Primary Button</Button>)
    }
}

假設(shè)React項(xiàng)目用的是React腳手架搭建,則在src目錄下的App.js文件中設(shè)置路由:

  render() {
    return (<HashRouter>
      <Switch>
        <Route exact={true} path="/login" component={Login} />
        <Route path="/home" component={First} />
        <Redirect to='/login' /> {/*/login和/home之外的路由直接跳轉(zhuǎn)到/login*/}
      </Switch>
    </HashRouter>)
  }

App.js完整代碼如下:

import React from 'react';
import { notification } from 'antd'
import { HashRouter, Route, Switch, Redirect } from 'react-router-dom';
import First from './First';
import Login from './Login';
import './App.css';

class App extends React.Component {
  constructor() {
    super();
    this.openNotificationWithIcon = type => {
      notification[type]({
        message: 'Notification Title',
        description:
          'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
      });
    }
  }

  clickHandle() {
    console.log("clicked!!!");
  }

  render() {
    return (<HashRouter>
      <Switch>
        <Route exact={true} path="/login" component={Login} /> {/**exact 防止混路由混合   如:輸入127.xx.xx.xx/home 中有/login頁(yè)面*/}
        <Route path="/home" component={First} />
        <Redirect to='/login' />
      </Switch>
    </HashRouter>)
  }
}

export default App;

項(xiàng)目目錄結(jié)構(gòu)如下:

React中配置子路由的實(shí)現(xiàn)方法

項(xiàng)目預(yù)覽效果如下:

React中配置子路由的實(shí)現(xiàn)方法

關(guān)于“React中配置子路由的實(shí)現(xiàn)方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI