【问题标题】:Set a style property in reactjs for all components of same type在 reactjs 中为所有相同类型的组件设置样式属性
【发布时间】:2019-05-18 08:22:57
【问题描述】:

我刚开始使用 ReactJS 和 MaterialUI,我很难理解样式与使用 CSS 有何不同。

我的意思是,在 CSS 中你可以为所有的 input 或 select 元素定义一个全局规则,但在 ReactJS 中你似乎做不到,你必须将类一个一个地传递给所有元素。我确定我遗漏了一些东西,但我还没有找到什么。

例如,如果我在一个表单中有 10 个 TextField(实际上我使用的是 react-admin 的 TextInput),我希望它们中的 10 个具有相同的宽度,而不必声明 style 对象,传递它使用withStyles(style) HOC 并一一设置className={classes.input}

【问题讨论】:

标签: reactjs jss


【解决方案1】:

简短的回答是 - 没有一种简单的方法可以在这里做你想做的事。

你有几个选择:

只需将类添加到每个组件中

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 组件

看到这个Software Engineering question of mine.

const MyTextInput = ({classes, ...rest}) => (
    <TextInput className = {classes.root} ...rest/> 
)

const styles = {
    root: {
       color: "red", 
    }
}

const MyForm = ({classes}) => (
    <Form> 
       <MyTextInput/> 
       <MyTextInput/> 
       <MyTextInput/>     
    </Form> 
); 

这似乎确实是不必要的样板等,但我认为从长远来看 - 这是将要存在一段时间的项目的最佳方法 - 就在整个应用程序中保持一致的设计模式而言。

【讨论】:

    猜你喜欢
    • 2010-11-03
    • 1970-01-01
    • 2013-01-05
    • 2020-11-19
    • 2010-10-28
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多