简体   繁体   中英

how to manage style in ReactJs

I am trying to learn react. I see a lot of style change inside java script so far. As far as I know, the style should onle be managed by css files. But I am not sure this rule also applies to 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? 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. You can declare your css in to your components in variables as well as in separate asssets directory.

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 . You should look into JSS so you can compile your css and later inject it into your component as props. Anyways there are a lot of resources that you can leverage from.

I prefer to connect external .css file - it's much more clean. If there is a need to keep styles in .js I would organize the code in that way:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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