如何在Material UI/JSS中定位复杂组件的兄弟姐妹/子组件



我目前在我的项目中使用Material UI。它运行良好,但我无法弄清楚的一件事是如何使用 JSS 设置子组件和同级组件的样式。

例如,材质 UI 的组件呈现如下:

<div class="MuiFormControl-root-36 MuiFormControl-marginNormal-37">
<label class="MuiFormLabel-root-45 MuiInputLabel-root-40 MuiInputLabel-formControl-41 MuiInputLabel-animated-44 MuiInputLabel-shrink-43" data-shrink="true">Field label</label>
<div class="MuiInput-root-52 MuiInput- 
formControl-53"><input aria-invalid="false" class="MuiInput-input-60" 
name="fieldname" type="text" value=""></div>
</div>

从Material UI文档中我知道这只是一些较低级别组件的包装器。我可以使用如下createMuiTheme()来定位这些单独的组件:

MuiInput: {
formControl: {
'label + &': {
marginTop: '30px'
}
},
root: {
'&$focused': {
boxShadow: '0px 3px 8px rgba(108, 108, 108, 0.16)'
},
borderRadius: '40px',
padding: '7px 16px',
background: 'white',
transition: 'box-shadow 0.2s',
}
}

我不明白的是,如何定位这些组件中的子项和/或兄弟姐妹 - 例如,在我的createMuiTheme函数中,如何定位MuiFormControl组件内的MuiFormLabel组件?或者,如果MuiFormLabel组件具有某个类,如何定位MuiInput组件?我知道我可以使用普通的CSS来定位元素(例如'&label'(,但我不知道如何定位组件/类,因为类名是动态的。

您可以直接设置 MuiFormLabel 组件的样式,为什么需要在 MuiFormControl 上设置它的样式?

您可以将每个组件包装在其自己的withStylesHOC 中并直接设置它们的样式。将样式保留在组件级别,而不是尝试从其父级设置嵌套组件的样式。

const styles = createStyles({
root: {
padding: 0
},
childRoot: {
color: 'red'
}
});
class MyComponent extends React.Component {

render() {
const { classes } = this.props;

return (
<ul className={classes.root}>
<fooComponent>
Bar
</fooComponent>
</ul>
);    
}
}
const fooComponent = withStyles(styles)((props) => {
return (
<li className={classes.childRoot}>
{ props.children }
</li>
);
});
export default withStyles(styles)(MyComponent);

更新:

或者,如果要在同一文件中使用多个组件,则可以将它们包装在自己的 HOC 中。

const renderFoo = withStyles(styles)((props) => {
const { bar, classes } = props;

return (
<div classNames={classes[bar]}>
Baz
</div>
)
}
const MyComponent = (props) => {
return (
<div>
<renderFoo variant='bar' />
</div>
}
export default MyComponent

最新更新