2017-09-26 56 views
0

場景整個應用程序是簡單的:只有一個AppBar(材料-UI)

  • 材料的UI與AppBar
  • AppBar不同爲我有每個路由。例如:
    • /ROUTE1:AppBar有iconElementLeft和iconElementRight
    • /路徑2:AppBar有iconElementLeft
    • /路徑3:AppBar有iconElementRight ...
  • 我不想重複代碼並在每條路徑中呈現AppBar
  • childrentitle也可能發生變化

這是一個推薦的方法?

雖然我可能有一個解決方案,我很想知道別人怎麼看這個案例,爲什麼不分享他們的想法?

我應該使用一種Main容器,它「偵聽」每個路由變化並根據每個路由呈現AppBar屬性?

我要舉一個例子讓您得到IDEIA :)

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> 

給,我你的想法。

+0

我們利用該lib實現了很好的appbar靈活性:https://github.com/camwest/react-slot-fill。現在,每個主頁都可以傳播到任何需要的appbar插槽。 – wakwak

回答

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功能父組件和它向下傳遞的,當叫捧出來的必備道具到AppBar組件道具,讓你的集裝箱無知的位置的對象。