[英]Extracting styles from material ui component
AppBar applies some styles for children of specific types. AppBar为特定类型的子代应用某些样式。 Unfortunately it happens only to direct children 不幸的是,这种情况只发生在直接的孩子身上
<AppBar title="first" iconElementRight={
<FlatButton label="first" />
}/>
<AppBar title="second" iconElementRight={
<div>
<FlatButton label="second" /> <!-- styles are not applied -->
</div>
}/>
Hopefully, it seems like AppBar component exposes getStyles method. 希望,似乎AppBar组件公开了getStyles方法。
exports.getStyles = getStyles;
Unfortunately I cannot figure out way to consume it. 不幸的是我无法弄清楚消耗它的方式。 Is there are any way do it rather than redefining all styles on my own? 有什么办法可以代替我自己重新定义所有样式?
PS I'm importing components in with import directive PS我要导入组件与导入指令
import AppBar from 'material-ui/AppBar';
MuiThemeProvider
adds a muiTheme
object to the context so you can get all the styles from there. MuiThemeProvider
将muiTheme
对象添加到上下文中,以便您可以从中获取所有样式。
Comp.contextTypes = {
muiTheme: React.PropTypes.object
}
render: function () {
let {appBar} = this.context.muiTheme; // appBar styles here
...
}
Sounds like you need a custom component to reroute the styles to your desired child. 听起来您需要一个自定义组件才能将样式重新路由到所需的孩子。 This version only forwards style
to the child and the rest stay on the wrapping component (a <div>
by default) but could be customized to your requirements. 此版本仅将style
转发给孩子,其余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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.