您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“react怎么實現側邊欄聯動頭部導航欄效果”,內容詳細,步驟清晰,細節處理妥當,希望這篇“react怎么實現側邊欄聯動頭部導航欄效果”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
項目中使用react+antd design+redux+react-reouter-dom
編寫路由表=》循環遍歷路由表=》渲染側邊欄=》單擊側邊欄獲取相應的標簽數據=》存入redux=》遍歷循環redux數據渲染頭部導航欄
const RouterTree = [ { key: 'num_one', title: { icon: '', text: 'text' }, children: [ { key: '1', text: 'options1', path: '/option1', component: '', isOutSide: true, } ] }, { key: 'num_two', title: { icon: '', text: 'text' }, children: [ { key: '2', text: 'text', path: '/option1', component: '', isOutSide: false } ] }, { key: 'num_three', title: { icon: '', text: 'text' }, children: [ { key: '3', text: 'text', path: '/option1', component: '', isOutSide: false } ] }, ] export default RouterTree
引入路由表,循環遍歷渲染側邊欄
import React, { Component } from 'react' import { Menu } from 'antd'; import { NavLink as Link, withRouter } from 'react-router-dom' import RouterTree from '@/modules/route.js' render() { const { activityKey } = this.state || {} return ( <div> <Menu onClick={this.handleClick} defaultSelectedKeys={['1']} defaultOpenKeys={['sub1']} selectedKeys={activityKey} mode="inline" inlineCollapsed={isToggle} > {RouterTree.map((item, index) => { return ( <SubMenu key={item.key} title={item.title.text} index={index} > {item.children && item.children.map((menuItem, menuIndex) => { return (<Menu.Item key={menuItem.key} index={menuIndex} > {menuItem.isOutSide ? <a href='http://www.baidu.com' rel="noopener noreferrer">baidu</a> : <Link to={menuItem.path}>{menuItem.text}</Link>} </Menu.Item>) })} </SubMenu>) })} </Menu> </div> )
由于單獨使用redux不便,項目中引用react-redux,redux-thunk。
這里將側邊欄拆分為兩個文件,一個是容器組件,一個為UI組件(以上的為UI組件)
容器組件為導出的組件,在容器組件中引入UI組件slide
import { connect } from 'react-redux' import { business } from '@/tools/index.js' import Slide from './slide' const { processedArr } = business const mapStoreToProps = (state) => { const { dynamicJump,activityKey} = state || {} let responseRoute = processedArr(dynamicJump) return { dynamicJump: [...responseRoute], activityKey:activityKey } } const mapDispatchToProps = (dispatch) => { return { updateRouter(item) { dispatch((dispatch) => { dispatch({ type: 'UPDATED_ROUTING', item: { ...item } }) }) }, activityKeys(key){ dispatch((dispatch)=>{ dispatch({ type:'ACTIVITY_KEY',key:key }) }) } } } export default connect(mapStoreToProps, mapDispatchToProps)(Slide)
在src下新建一個store文件
import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk'; import { routerMiddleware } from 'react-router-redux' let createHistory = require('history').createBrowserHistory let history = createHistory() let routerWare = routerMiddleware(history) const dynamicJump = { dynamicJump: '這里設置默認值'(一般存放在session中), activityKey: '這里設置默認值', } const reducers = function (state = dynamicJump, action) { switch (action.type) { case 'UPDATED_ROUTING': state.dynamicJump =action.item break; case 'ACTIVITY_KEY': if (action.key !== undefined) { state.activityKey = action.key } break; default: break; } return { ...state } } const store = createStore(reducers, applyMiddleware(thunk, routerWare)) // 訂閱事件 store.subscribe(() => { let state = store.getState(); sessionStorage.setItem('dynamicJump',JSON.stringify(state.dynamicJump)) sessionStorage.setItem('activityKey',JSON.stringify(state.activityKey)) }) export default store
在根目錄下將其注入進去(注意文件的引入位置)
import {Provider} from 'react-redux' import store from './store/index.js' ReactDOM.render( <Provider store={store}><App /></Provider>, document.getElementById('root') );
import { connect } from 'react-redux' import { push } from 'react-router-redux' import { business } from '@/tools/index.js' import Header from './head.jsx' const { processedArr } = business const mapStoreToProps = (state) => { const { dynamicJump, activityKey } = state let newRouteArr = processedArr(dynamicJump) return { dynamicJump: [...newRouteArr], activityKey: activityKey } } const mapDispatchToProps = (dispatch) => { return { removeKey(itemKey) { dispatch((dispatch, getStore) => { const { dynamicJump } = getStore() || {} let removeArr = processedArr(dynamicJump) const indexes = removeArr.findIndex((item) => item.key === itemKey) // 點擊頭部導航條的刪除(即刪除保存在redux的數組元素即可) if (removeArr.length > 1) { removeArr.splice(indexes, 1) } // 刪除之后跳轉到刪除元素的前一個元素的路由地址 let path = removeArr[indexes - 1] ? removeArr[indexes - 1].path : '/option1' let keys = removeArr[indexes - 1] ? removeArr[indexes - 1].key : 0 if(keys===0){ keys=removeArr[0].key } dispatch({ type: 'UPDATED_ROUTING', item: { ...removeArr }, }) dispatch({ type: 'ACTIVITY_KEY', key: keys }) // 這里進行跳轉 dispatch(push(path)) }) }, changeActiveKey(key) { dispatch((dispatch) => { dispatch({ type: 'ACTIVITY_KEY', key: key }) }) } } } export default connect(mapStoreToProps, mapDispatchToProps)(Header)
這里存在著:如果刪除頭部組件的其中一個導航,那么需要跳轉到該導航(刪除的)的前一個路由地址,而這個操作在UI組件中是不方便的,這里我采取的方法是引入“history”模塊(詳細代碼請移步到store.js),然后在容器組件中使用dispatch(push(path))跳轉,也可以使用更為簡單的方法,直接在容器組件中引入react-router的withRouter,包裹在最外層即:export default withRouter(connect(mapStoreToProps, mapDispatchToProps)(Header))
render(){ const { dynamicJump } = this.props || {} const { activeKey } = this.state || {} <Tabs hideAdd onChange={this.onChange} activeKey={activeKey} type="line" onEdit={this.onEdit} className='tabs' > { dynamicJump.map((item) => ( <TabPane tab={<Link to={item.path}>{item.text}</Link>} key={item.key} /> ))} </Tabs> }
對于key值,可以使用react新增的鉤子函數:getDerivedStateFromProps進行判斷是否更行
static getDerivedStateFromProps(nextProps, preState) { const { activityKey, dynamicJump } = nextProps || {} const { activeKey } = preState || {} if (activityKey !== activeKey) { return { activeKey: activityKey } } return { allRoute: dynamicJump } } remove = targetKey => { this.removeKey(targetKey) } removeKey(key) { this.props.removeKey(key) }
讀到這里,這篇“react怎么實現側邊欄聯動頭部導航欄效果”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。