我刚开始使用ReactJS和MaterialUI,我很难理解样式与使用CSS的区别。
我的意思是,在CSS中,你可以为所有输入或选择元素定义一个全局规则,但在ReactJS中,你似乎无法做到这一点,你必须将类逐个传递给所有元素。我确信我错过了什么,但我没有找到什么。
例如,如果我在Form中有10个TextField(事实上我使用的是react admin中的TextInput(,我希望它们中的10个具有相同的宽度,而不必声明style
对象,使用withStyles(style)
HOC传递它,并逐个设置className={classes.input}
。
简单的答案是-在这里没有一种简单的方法可以实现您想要的。
你有几个选择:
只需将类添加到每个组件中
const MyForm = ({classes}) => (
<Form>
<TextInput className = {classes.textInput} />
<TextInput className = {classes.textInput}/>
<TextInput className = {classes.textInput}/>
</Form>
)
const styles = {
textInput: {
color: "red"
}
}
这样做的缺点是重复。
使用嵌套选择器直接设置dom元素输入的样式
const MyForm = ({classes}) => (
<Form className={classes.root}>
<TextInput/>
<TextInput/>
<TextInput/>
</Form>
)
const styles = {
root: {
"& input" {
color: "red",
}
}
}
这将直接为input
dom元素设置样式,而不是React组件本身。这样做的缺点是,你可能最终会对你不打算的输入进行样式化。然而,我发现这是做样式表等事情的最佳方式。
创建自己的高阶组件库以包装Material UI组件
请参阅我的软件工程问题。
const MyTextInput = ({classes, ...rest}) => (
<TextInput className = {classes.root} ...rest/>
)
const styles = {
root: {
color: "red",
}
}
const MyForm = ({classes}) => (
<Form>
<MyTextInput/>
<MyTextInput/>
<MyTextInput/>
</Form>
);
这看起来确实是不必要的样板等,但我认为从长远来看——这是一个即将存在一段时间的项目的最佳方法——在整个应用程序中保持一致的设计模式。