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

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

问题描述

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

const MyDiv = React.createClass({渲染:函数(){常量样式 = {白颜色',字体大小:200};返回 

有一个美好而富有成效的一天!

;}});

我是否应该以这种方式处理所有样式,并且在我的 CSS 文件中完全没有指定样式?

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

两者都做一点似乎很奇怪和混乱 - 在调整样式时需要检查两个地方.

解决方案

目前还没有很多最佳实践".对于 React 组件,我们这些使用内联样式的人仍在进行大量实验.

有许多不同的方法:反应内联样式库比较图表

全有还是全无?

我们所说的风格"其实包含不少概念:

  • 布局 - 元素/组件与其他元素/组件的关系
  • 外观——元素/组件的特征
  • 行为和状态——元素/组件在给定状态下的外观

从状态样式开始

React 已经在管理组件的状态,这使得状态和行为的样式自然适合与组件逻辑共置.

与其构建组件以使用条件状态类进行渲染,不如考虑直接添加状态样式:

//带有状态类的典型组件//对状态使用内联样式<li className='todo-list__item'样式={(item.complete) ?style.complete : {}}/>

请注意,我们使用一个类来设置外观的样式,但不再对状态和行为使用任何带有 .is- 前缀的类.

我们可以使用 Object.assign (ES6) 或 _.extend (underscore/lodash) 来添加对多种状态的支持:

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

定制化和可重用性

既然我们正在使用 Object.assign,那么让我们的组件可以以不同的样式重用变得非常简单.如果我们想覆盖默认样式,我们可以在调用站点使用 props 来实现,如下所示:<TodoItem DueStyle={ fontWeight: "bold" }/>.实现如下:

  • 布局

    就我个人而言,我认为内联布局样式没有令人信服的理由.有许多很棒的 CSS 布局系统.我只用一个.

    也就是说,不要将布局样式直接添加到您的组件中.用布局组件包裹你的组件.这是一个例子.

    //这将您的组件耦合到布局系统//它降低了组件的可重用性<用户徽章className="col-xs-12 col-sm-6 col-md-8"名字=迈克尔"lastName="陈"/>//这更容易维护和更改<div class="col-xs-12 col-sm-6 col-md-8"><用户徽章名字=迈克尔"lastName="陈"/>

    为了布局支持,我经常尝试将组件设计为 100% widthheight.

    外观

    这是内联风格"辩论中最具争议的领域.归根结底,这取决于您设计的组件以及您的团队对 JavaScript 的舒适度.

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

    我喜欢 Radium,因为这些难点的语法旨在模拟 SASS 的语法.

    代码组织

    通常你会在模块之外看到一个样式对象.对于待办事项列表组件,它可能看起来像这样:

    var 样式 = {根: {显示:块"},物品: {颜色:黑色"完全的: {textDecoration: "line-through"},到期的: {红色"}},}

    getter 函数

    向模板中添加一堆样式逻辑可能会有些混乱(如上所示).我喜欢创建 getter 函数来计算样式:

    React.createClass({getStyles: 函数 () {返回 Object.assign({},item.props.complete &&样式.完成,item.props.due &&样式.由于,item.props.due &&this.props.dueStyles);},渲染:函数(){return <li style={this.getStyles()}>{this.props.item}</li>}});

    进一步观察

    我在今年早些时候的 React Europe 上更详细地讨论了所有这些:内联样式以及何时最好只使用 CSS".

    我很高兴在您一路上有新发现时提供帮助:) 打我 -> @chantastic

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

    const MyDiv = React.createClass({
      render: function() {
        const 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天全站免登陆