React.js inline style best practices

2019-01-03 03:39发布

I'm aware that you can specify styles within React classes, like this:

var MyDiv = React.createClass({
  render: function() {
    var style = {
      color: 'white',
      fontSize: 200
    };

    return <div style={style}> Have a good and productive day! </div>;
  }
});

Should I be aiming to do all styling this way, and have no styles at all specified in my CSS file?

Or should I avoid inline styles completely?

It seems odd and messy to do a little bit of both - two places would need to be checked when tweaking styling.

14条回答
Evening l夕情丶
2楼-- · 2019-01-03 04:31

I use inline styles extensively within my React components. I find it so much clearer to colocate styles within components because it's always clear what styles the component does and doesn't have. Plus having the full power of Javascript at hand really simplifies more complex styling needs.

I wasn't convinced at first but after dabbling in it for several months, I'm fully converted and am in process of converting all my CSS to inline or other JS-driven css methods.

This presentation by Facebook employee and React contributor "vjeux" is really helpful as well — https://speakerdeck.com/vjeux/react-css-in-js

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-03 04:32

I usually have scss file associated to each React component. But, I don't see reason why you wouldn't encapsulate the component with logic and look in it. I mean, you have similar thing with web components.

查看更多
登录 后发表回答