React.js内联样式最佳实践

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


var MyDiv = React.createClass({

  render: function() {

    var style = {

      color: 'white',

      fontSize: 200

    };


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

  }

});

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


或者我应该完全避免使用内联样式?


做两件事似乎很奇怪和混乱 - 在调整样式时需要检查两个地方。


富国沪深
浏览 1647回答 3
3回答

拉风的咖菲猫

目前还没有很多“最佳实践”。对于React组件,我们这些使用内联样式的人仍然在进行实验。有许多方法变化很大:React内联样式的lib比较图表全有或全无?我们所谓的“风格”实际上包含了很多概念:布局 - 元素/组件与其他元素的关系外观 - 元素/组件的特征行为和状态 - 元素/组件在给定状态下的外观从状态样式开始React已经在管理组件的状态,这使得状态和行为的样式自然适合与组件逻辑进行共置。不要使用条件状态类构建要呈现的组件,而是考虑直接添加状态样式:// Typical component with state-classes<li&nbsp;&nbsp;className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })} />// Using inline-styles for state<li className='todo-list__item'&nbsp;style={(item.complete) ? styles.complete : {}} />请注意,我们使用类来设置外观样式,但不再使用任何带.is-前缀的类来处理状态和行为。我们可以使用Object.assign(ES6)或_.extend(下划线/ lodash)来添加对多个状态的支持:// Supporting multiple-states with inline-styles<li 'todo-list__item'&nbsp;style={Object.assign({}, item.complete && styles.complete, item.due && styles.due )}>定制和可重用性现在我们正在使用Object.assign它变得非常简单,使我们的组件可以重复使用不同的样式。如果我们想要覆盖默认样式,我们可以在带有props的调用站点上这样做,如下所示:<TodoItem dueStyle={ fontWeight: "bold" } />。像这样实现:<li 'todo-list__item'&nbsp;style={Object.assign({},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;item.due && styles.due,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;item.due && this.props.dueStyles)}>布局就个人而言,我没有看到内联布局样式的令人信服的理由。有很多很棒的CSS布局系统。我只想用一个。也就是说,不要直接向组件添加布局样式。使用布局组件包装组件。这是一个例子。// This couples your component to the layout system// It reduces the reusability of your component<UserBadge&nbsp;className="col-xs-12 col-sm-6 col-md-8"&nbsp;firstName="Michael"&nbsp;lastName="Chan" />// This is much easier to maintain and change<div class="col-xs-12 col-sm-6 col-md-8">&nbsp; <UserBadge&nbsp; &nbsp;firstName="Michael"&nbsp; &nbsp;lastName="Chan" /></div>对于布局支持,我经常尝试将组件设计为100% width和height。出现这是“内联式”辩论中最具争议的领域。最终,它取决于您的设计组件以及使用JavaScript的团队的舒适度。有一件事是肯定的,你需要图书馆的协助。浏览器状态(:hover,:focus)和媒体查询在原始React中很痛苦。我喜欢Radium,因为这些硬件的语法设计用于模拟SASS的语法。代码组织通常,您会在模块外部看到样式对象。对于todo-list组件,它可能看起来像这样:var styles = {&nbsp; root: {&nbsp; &nbsp; display: "block"&nbsp; },&nbsp; item: {&nbsp; &nbsp; color: "black"&nbsp; &nbsp; complete: {&nbsp; &nbsp; &nbsp; textDecoration: "line-through"&nbsp; &nbsp; },&nbsp; &nbsp; due: {&nbsp; &nbsp; &nbsp; color: "red"&nbsp; &nbsp; }&nbsp; },}吸气功能在模板中添加一堆样式逻辑可能会有点混乱(如上所示)。我喜欢创建getter函数来计算样式:React.createClass({&nbsp; getStyles: function () {&nbsp; &nbsp; return Object.assign(&nbsp; &nbsp; &nbsp; {},&nbsp; &nbsp; &nbsp; item.props.complete && styles.complete,&nbsp; &nbsp; &nbsp; item.props.due && styles.due,&nbsp; &nbsp; &nbsp; item.props.due && this.props.dueStyles&nbsp; &nbsp; );&nbsp; },&nbsp; render: function () {&nbsp; &nbsp; return <li style={this.getStyles()}>{this.props.item}</li>&nbsp; }});进一步观看我在今年早些时候在React Europe上更详细地讨论了所有这些:内联样式以及何时最好'只使用CSS'。我很乐意帮助您沿途创造新的发现:)打我 - > @chantastic
打开App,查看更多内容
随时随地看视频慕课网APP