简体   繁体   English

如何在ReactJs中管理样式

[英]how to manage style in ReactJs

I am trying to learn react. 我正在尝试学习反应。 I see a lot of style change inside java script so far. 到目前为止,我在Java脚本中看到了很多样式更改。 As far as I know, the style should onle be managed by css files. 据我所知,样式应该仅由css文件管理。 But I am not sure this rule also applies to React. 但是我不确定这个规则是否也适用于React。 What is the best practice for react. 什么是做出反应的最佳实践。 For instance, is the following code a clean code, or is changing the style in the React component a smell and need to be refactored? 例如,下面的代码是干净的代码,还是在React组件中更改样式是难闻的气味并需要重构? If so, how it could be refactored? 如果是这样,如何将其重构?

“const Color = ({ title, color}) =>
    <section className="color">
        <h1>{title}</h1>
        <div className="color" 
             style={{ backgroundColor: color }}>
        </div>
    </section>”

That is totally depends on our requirement and preferences. 这完全取决于我们的要求和偏好。 Inline styles are concerned with only component they are written into. 内联样式仅涉及写入它们的组件。 You can structure css based on your components so it becomes reusable. 您可以根据组件构造CSS,从而使其可重用。 You can declare your css in to your components in variables as well as in separate asssets directory. 您可以在变量以及单独的asssets目录中的组件中声明css。

Well it is more about code readability and re-usability. 好吧,它更多是关于代码的可读性和可重用性。 Webpack writes your all css/scss in a single file and inject into your index.html . Webpack将所有css / scss写入单个文件中,然后注入index.html You should look into JSS so you can compile your css and later inject it into your component as props. 您应该研究JSS,以便可以编译CSS,然后将其作为道具注入到组件中。 Anyways there are a lot of resources that you can leverage from. 无论如何,您可以利用很多资源。

I prefer to connect external .css file - it's much more clean. 我更喜欢连接外部.css文件-它更干净。 If there is a need to keep styles in .js I would organize the code in that way: 如果需要在.js中保留样式,则可以通过以下方式组织代码:

const styles = {
color: 'red',
fontSize: '2rem',
backgroundColor: 'forestgreen'
}

And I would apply the styles I need just like here: 我将像下面这样应用我需要的样式:

<div style={{color: styles.color, fontSize: styles.fontSize}}></div>

Or, If I need to apply all styles: 或者,如果我需要应用所有样式:

<div style={styles}></div>

您还可以使用样式化的组件https://www.styled-components.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM