【问题标题】:React — have active item state stay with menu component when loaded into new pageReact — 当加载到新页面时,活动项状态与菜单组件保持一致
【发布时间】:2016-09-23 10:44:32
【问题描述】:

我有一个菜单组件在加载到不同页面时会丢失其状态。我是 React noobie,并试图找出管理“活动”菜单类的最佳方法。我正在使用 react-router,我认为我让这变得比它需要的更困难

导航包含在不同的页面中,如下所示:

// some component
<header className="autohide header-down">
  <Nav />
</header>

// some other component
<footer className="autohide header-down">
  <Nav />
</footer>

我在组件内部使用它来设置“活动”菜单项,但是(我应该预料到这一点)当导航组件被加载到新页面时,它会失去活动状态:

getInitialState(){
  return {
    selected:''
  }
},
setFilter(filter) {
  this.setState({selected  : filter})
  this.props.onChangeFilter(filter);
},
isActive(value){
  return 'nav-link '+((value===this.state.selected) ?'active':'');
},
onClick(){

},
render()...

每个链接上都有这个:

<Link className={this.isActive('settings')} onClick={this.setFilter.bind(this, 'settings')} to="/settings">SETTINGS</Link>

想法?

【问题讨论】:

  • 你需要将状态存储在组件之外并传入。你用什么做路由器?
  • @Blairanderson 我正在使用 react-router(我认为它内置了主动功能,但我不知道如何使用它)。

标签: reactjs


【解决方案1】:

对于您当前的设置,只需将 active 属性从每个组件传递到您的标题:

const Dashboard = React.createClass({
  render() {
    return <div>
      <Nav active="dashboard" />
    </div>
  }
})

const About = React.createClass({
  render() {
    return <div>
      <Nav active="about" />
    </div>

  }
})

const Messages = React.createClass({
  render() {
    return <div>
      <Nav active="messages" />
      // other stuff
    </div>
  }
})

const Nav = React.createClass({
  isActive(value){
    return 'nav-link '+((value===this.props.active) ?'active':'');
  },
  render() {
    return <div>
      <Link className={this.isActive("settings")}>Settings</Link>
      <Link className={this.isActive("dashboard")}>Dashboard</Link>
    </div>
  }
})



render((
  <Router>
    <Route path="/" component={App}>
      <IndexRoute component={Dashboard} />
      <Route path="about" component={About} />
      <Route path="inbox" component={Inbox}>
        <Route path="messages/:id" component={Messages} />
      </Route>
    </Route>
  </Router>
), document.body)

【讨论】:

  • 在 Nav var 中,我看不到活动项目的 className 是如何设置的。即,...
  • 我搞定了...只是将 active={"this.isActive"...} 更改为 className={this.isActive...}
猜你喜欢
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 2011-05-14
  • 2012-12-27
  • 1970-01-01
相关资源
最近更新 更多