2016-08-04 15 views
0

應用條形碼爲特定類型的子項應用了一些樣式。遺憾的是它只發生直接孩子從素材UI組件中提取樣式

<AppBar title="first" iconElementRight={ 
    <FlatButton label="first" /> 
}/> 
<AppBar title="second" iconElementRight={ 
    <div> 
     <FlatButton label="second" /> <!-- styles are not applied --> 
    </div> 
}/> 

jsfiddle

希望,好像AppBar組件公開getStyles方法。

exports.getStyles = getStyles; 

不幸的是,我不知道如何使用它。有沒有什麼辦法,而不是自己重新定義所有風格?

PS 我進口成分與進口指令

import AppBar from 'material-ui/AppBar'; 
+0

你想要什麼來實現呢?從AppBar獲取樣式並覆蓋''text color?或者只是從AppBar獲取樣式? – QoP

+0

@QoP:我想製作FlatButton和一些IconMenu,我將它們作爲iconElementRight的直接子代指定。要做到這一點,我打算從AppBar中獲取樣式,併爲我的元素重寫它(應該關於顏色和位置)。 –

回答

1

MuiThemeProvider增加了muiTheme對象的背景,所以你可以從那裏得到的所有樣式。

Comp.contextTypes = { 
    muiTheme: React.PropTypes.object 
} 

render: function() { 
     let {appBar} = this.context.muiTheme; // appBar styles here 
     ... 
} 

jsfiddle

+0

謝謝。我認爲這比在自己的組件中硬編碼顏色更好。但是,從https://github.com/callemall/material-ui/blob/master/src/AppBar/AppBar.js#L55獲取確切樣式會很好,那麼我不需要爲其他屬性+它將在AppBar更改上自動更新。它似乎也導出了getStyles函數。你認爲有辦法以某種方式稱呼它嗎? –

+0

我不認爲這是可能的,看起來像一個「內部」功能。你可以嘗試使用'material-ui/AppBar/AppBar'中的'import {getStyles}來導入它,並使用getStyles(this.props,this.context)來調用它,但不知道它是否可以工作。 – QoP

1

聽起來像是你需要一個定製的組件樣式重新路由到您想要的孩子。此版本僅將style轉發給孩子,其餘的繼續留在包裝組件上(默認情況下爲<div>),但可以根據您的要求進行自定義。

 const StyleDelegate = function (props) { 
 
    const {component: Component, children, style, ...rest} = props; 
 
    // pass style to the only child and everything else to the component 
 
    // could be further customized for other props 
 
    return (
 
     <Component {...rest}> 
 
      {React.cloneElement(children, {style})} 
 
     </Component> 
 
); 
 
}; 
 

 
StyleDelegate.defaultProps = { 
 
    component: 'div' 
 
}; 
 

 
const AppBar = function (props) { 
 
    return (
 
    <div> 
 
     {props.title} 
 
     {React.cloneElement(props.iconElementRight, {style: {color: 'blue'}})} 
 
    </div> 
 
); 
 
} 
 
    
 
ReactDOM.render(<AppBar 
 
        iconElementRight={<StyleDelegate><span>Icon</span></StyleDelegate>} 
 
        title="title" />, 
 
       document.querySelector('#app') 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>