NavDropdown未设置为激活时菜单项子链接激活

问题描述 投票:0回答:2

我现在面临这个问题上选择菜单项的子链接的反应,引导NavDropdown然后NavDropdown标题不为主动方式。

  1. 我NavDropDown代码: <NavDropdown eventKey={4} title="Manage User" id="basic-nav-dropdown"> <LinkContainer to="/users/add"> <MenuItem eventKey={4.1}>Add User</MenuItem> </LinkContainer> <IndexLinkContainer to="/users"> <MenuItem eventKey={4.2}>View User</MenuItem> </IndexLinkContainer> </NavDropdown>
  2. 路线 <Route path="/users" component={Users}> <IndexRoute component={UserList} /> <Route path="/users/add" component={AddUser} /> <Route path="/users/:id/edit" component={EditUser} /> </Route>

该NavDropDown标题“管理用户”甚至菜单项已被路由和选定后,从来没有为主动方式。

reactjs react-router react-bootstrap
2个回答
0
投票

我当时也面临着类似的问题,我解决了它这样的。

您需要定义activeKey支撑在<Nav >,这个值activeKey这将决定哪些链接是有效的。

class Navigation extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
          activeKey : 0
        }

        this.toggleClass = this.toggleClass.bind(this);
    }

    componentDidMount(){
        if(window.location.pathname === "/users/add") {
          this.setState({ activeKey : 4.1 });
        } else if(window.location.pathname === "/users") {
          this.setState({ activeKey : 4.2 });
        }
    }

    toggleClass(e) {

      if(e.target.pathname === "/users/add") {
        this.setState({ activeKey : 4.1 });
      } else if(e.target.pathname === "/users") {
        this.setState({ activeKey : 4.2 });
      }
    }

    render() {

        return (
            <Navbar inverse fluid collapseOnSelect>
              <Navbar.Collapse>
                <Nav pullRight activeKey={this.state.activeKey}>
                  <NavDropdown eventKey={4} title="Manage User" id="basic-nav-dropdown">
                    <LinkContainer to="/users/add" onClick={this.toggleClass}>
                      <MenuItem eventKey={4.1}>Add User</MenuItem>
                    </LinkContainer>
                    <IndexLinkContainer to="/users" onClick={this.toggleClass}>
                      <MenuItem eventKey={4.2}>View User</MenuItem>
                    </IndexLinkContainer>
                  </NavDropdown>
                </Nav>
              </Navbar.Collapse>
            </Navbar>
        )
    }
}

希望这可以帮助你。


0
投票

我解决这样这个问题:

第一步。我在组件的状态宣布activeKey这将决定哪些NavDropDown活跃

 constructor(props) {
    super(props);
    this.state = { activeKey: 1 };
 }

第二步。该事件处理函数来处理onSelect事件。拿到钥匙事件截断它并将其设置为“activeKey”状态

 handleSelect = (key) => {
    this.setState({ activeKey: Math.trunc(key) });
 }

第三步。调用上述导航的功能ONSELECT并传递“activeKey”值activeKey属性:

<Nav 
  activeKey={this.activeKey} 
  onSelect={this.handleSelect}> 
</Nav>

它的工作完美。

© www.soinside.com 2019 - 2024. All rights reserved.