解決手動輸入地址,antd的Menu切換沒有相應改變的bug

antd的Menu組件的觸發狀態是由selectedKeys屬性決定的
當我們在一個頁面組件中使用了Menu,想要當前的path與antd的Menu始終保持一致,我們叫想辦法獲取到path,並且修改Menu的selectedKeys
這裏我們把Menu寫進一個NavBar組件裏
所以我們在父組件打印props是可以獲取到pathname的,我們要把它作爲props傳遞給子組件
子組件在cdm(componentDidMount)函數中處理

  componentDidMount() {
    // location 包括 pathname search  hash  state
    this.handleSetSelectedKeys(this.props.location.pathname);
  }
  handleSetSelectedKeys(pathname) {
    // /admin = ["/","admin"]
    // 根據'/'把路由地址分割成一個數組
    const temp = pathname.split('/');
    // 如果數組的長度小於2,表示的是隻有根路徑/,設置爲Home. 否則取數組中第二個值
    const key = temp && temp.length < 2 ? 'home' : temp[1];
    this.setState({
      selectedKeys: [key]
    });
  }

最後

 <Menu
          className={style['menu-left']}
          mode="horizontal"
          defaultSelectedKeys={['home']}
          selectedKeys={this.state.selectedKeys}
        >
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章