React.js内联样式的最佳实践 [英] React.js inline style best practices

查看:224
本文介绍了React.js内联样式的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以在React类中指定样式,例如:

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

return< div style = {style}>有一个好的和富有成效的一天!< / div> ;;
}
}

我应该以这种方式做所有样式,并且在我的CSS中没有指定样式文件?



还是应该完全避免内联样式?



看起来很奇怪,的两个地方,当调整造型时需要检查。

解决方案

还没有很多最佳实践。我们使用内联样式,对于React组件,仍然是非常多的实验。



有很多方法,变化很大:修改内嵌式库比较图表



全部或全部?



我们所说的style实际上包含了几个概念:




  • 布局 - 元素/组件如何与他人的关系看起来

  • 外观 - 元素/组件的特性

  • 行为和状态 - 元素/组件在给定状态下的外观



从状态样式开始



React已经在管理组件的状态,这使得样式状态和行为<



不要使用条件状态类来构建组件,而是直接添加状态样式:

  //具有状态类的典型组件
< li
className = {classnames({'todo-list__item' :true,'is-complete':item.complete})} />


//使用内联样式的状态
< li className ='todo-list__item'
style = {(item.complete)? styles.complete:{}} />

请注意,我们使用类来风格外观状态和行为使用任何 .is - 前缀类。



Object.assign (ES6)或 _。extend (下划线/ lodash)添加对多个状态的支持: p>

  //使用内联样式支持多状态
< li'todo-list__item'
style = {Object.assign({},item.complete&& styles.complete,item.due&& styles.due)}>



自定义和可重用性



're using Object.assign 它变得非常简单,使我们的组件可以使用不同的样式。如果我们要覆盖默认样式,我们可以在调用站点使用props这样做:< TodoItem dueStyle = {fontWeight:bold} /> 。实现如下:

 < li'todo-list__item'
style = {Object.assign({},
item.due&& styles.due,
item.due&& this.props.dueStyles)}>



布局



看到引人注目的原因来内联布局样式。有很多伟大的CSS布局系统在那里。我只是使用一个。



也就是说,不要直接添加布局样式到你的组件。使用布局组件包装组件。这是一个例子。

  //这将您的组件与布局系统相结合
//它减少了组件
< UserBadge
className =col-xs-12 col-sm-6 col-md-8
firstName =Michael
lastName =Chan >

//这更容易维护和更改
< div class =col-xs-12 col-sm-6 col-md-8>
< UserBadge
firstName =Michael
lastName =Chan/>
< / div>

对于布局支持,我经常尝试将组件设计为 100% / code> width height



外观



这是内联式辩论中最有争议的领域。最终,这取决于您的设计组件和JavaScript的团队的舒适度。



有一件事是肯定的,你需要图书馆的帮助。浏览器状态(:hover :focus )和媒体查询在原始React中是痛苦的。 >

我喜欢 Radium ,因为这些硬件的语法是为了模拟



通常,你会在模块外部看到一个样式对象。对于todo-list组件,它可能看起来像这样:

  var styles = {
root:{
display:block
},
item:{
color:black

complete:{
textDecoration:通过
},

到期:{
color:red
}
},
}



getter函数



在模板中添加一堆样式逻辑得到一点凌乱(如上所示)。我喜欢创建getter函数来计算样式:

  React.createClass({
getStyles:function b $ b return Object.assign(
{},
item.props.complete&& styles.complete,
item.props.due&& styles.due,
item.props.due&& this.props.dueStyles
);
},

render:function(){
return< li style = {this.getStyles()}> {this.props.item}< / li>
}
});



进一步观察



这些在今年早些时候在React欧洲更详细:内联样式,什么时候最好只使用CSS



我很乐意帮助您沿着新方向发现:)命中我 - > @ chantastic


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.

解决方案

There aren't a lot of "Best Practices" yet. Those of us that are using inline-styles, for React components, are still very much experimenting.

There are a number of approaches that vary wildly: React inline-style lib comparison chart

All or nothing?

What we refer to as "style" actually includes quite a few concepts:

  • Layout — how an element/component looks in relationship to others
  • Appearance — the characteristics of an element/component
  • Behavior and state — how an element/component looks in a given state

Start with state-styles

React is already managing the state of your components, this makes styles of state and behavior a natural fit for colocation with your component logic.

Instead of building components to render with conditional state-classes, consider adding state-styles directly:

// Typical component with state-classes
<li 
 className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })} />


// Using inline-styles for state
<li className='todo-list__item'
 style={(item.complete) ? styles.complete : {}} />

Note that we're using a class to style appearance but no longer using any .is- prefixed class for state and behavior.

We can use Object.assign (ES6) or _.extend (underscore/lodash) to add support for multiple states:

// Supporting multiple-states with inline-styles
<li 'todo-list__item'
 style={Object.assign({}, item.complete && styles.complete, item.due && styles.due )}>

Customization and reusability

Now that we're using Object.assign it becomes very simple to make our component reusable with different styles. If we want to override the default styles, we can do so at the call-site with props, like so: <TodoItem dueStyle={ fontWeight: "bold" } />. Implemented like this:

<li 'todo-list__item'
 style={Object.assign({},
         item.due && styles.due,
         item.due && this.props.dueStyles)}>

Layout

Personally, I don't see compelling reason to inline layout styles. There are a number of great CSS layout systems out there. I'd just use one.

That said, don't add layout styles directly to your component. Wrap your components with layout components. Here's an example.

// This couples your component to the layout system
// It reduces the reusability of your component
<UserBadge
 className="col-xs-12 col-sm-6 col-md-8"
 firstName="Michael"
 lastName="Chan" />

// This is much easier to maintain and change
<div class="col-xs-12 col-sm-6 col-md-8">
  <UserBadge
   firstName="Michael"
   lastName="Chan" />
</div>

For layout support, I often try to design components to be 100% width and height.

Appearance

This is the most contentious area of the "inline-style" debate. Ultimately, it's up to the component your designing and the comfort of your team with JavaScript.

One thing is certain, you'll need the assistance of a library. Browser-states (:hover, :focus), and media-queries are painful in raw React.

I like Radium because the syntax for those hard parts is designed to model that of SASS.

Code organization

Often you'll see a style object outside of the module. For a todo-list component, it might look something like this:

var styles = {
  root: {
    display: "block"
  },
  item: {
    color: "black"

    complete: {
      textDecoration: "line-through"
    },

    due: {
      color: "red"
    }
  },
}

getter functions

Adding a bunch of style logic to your template can get a little messy (as seen above). I like to create getter functions to compute styles:

React.createClass({
  getStyles: function () {
    return Object.assign(
      {},
      item.props.complete && styles.complete,
      item.props.due && styles.due,
      item.props.due && this.props.dueStyles
    );
  },

  render: function () {
    return <li style={this.getStyles()}>{this.props.item}</li>
  }
});

Further watching

I discussed all of these in more detail at React Europe earlier this year: Inline Styles and when it's best to 'just use CSS'.

I'm happy to help as you make new discoveries along the way :) Hit me up -> @chantastic

这篇关于React.js内联样式的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆