整个应用只有一个AppBar(material-ui)

时间:2017-09-26 20:19:01

标签: reactjs material-ui

场景很简单:

  • material-ui with AppBar
  • AppBar对于我拥有的每条路线都有所不同。例如:
    • / route1:AppBar有iconElementLeft和iconElementRight
    • / route2:AppBar有iconElementLeft
    • / route3:AppBar有iconElementRight ...
  • 我不想复制代码并在每条路线中呈现AppBar
  • childrentitle也可能会改变

对此推荐什么方法?

虽然我可能有解决方案,但我很想知道其他人对此案例的看法以及为何不分享他们的想法?

我应该使用一种Main容器来监听"每条路线改变并根据每条路线呈现AppBar属性?

我要举个例子让你得到这个想法:)

renderElementLeft = (location) => {
  if (location is /route1) {
    return <IconButton>...</IconButton>
  }

  if (location is /route2) {
    return <FlatButton label="..." />
  }

  return null // or <div />
}

renderElementRight = (location) => {
  if (location is /route1) {
    return <FlatButton label="..." />
  }

  if (location is /route2) {
    return null // or <div />
  }

  return <IconButton>...</IconButton>
}


const Container = ({ children, location }) => 
  <div>
    <AppBar
      iconElementLeft={renderElementLeft(location)}
      iconElementRight={renderElementRight(location)}
      ...
    />
    {children}
  </div>

给我你的想法。

1 个答案:

答案 0 :(得分:0)

这是您原始想法的修改版本。

    renderElements = (location) => {
    if (location is /route1) {
        return {iconElementLeft:<IconButton>...</IconButton>,
        iconElementRight:<FlatButton label="..." />};
    }

    if (location is /route2) {
        return {iconElementLeft:<FlatButton label="..." />,
        iconElementRight:null};
    }

    return {};
    }


    const Container = ({ children, location }) => 
    <div>
        <AppBar
        {...renderElements(location)}
        />
        {children}
    </div>

您还可以将renderElements函数移动到父组件并将其作为prop传递下去,当被调用时,将必要的道具分发给AppBar组件,让Container忽略位置对象。