react样式工具介绍

953 查看

react样式工具有许许多多,本文将其分为四类分别介绍总结,方便日常项目开发过程中进行选择和组合使用。

四类工具

类型一:方法论

方法论类型的工具是指导你如何使用css,通过遵循标准规范,能够避免犯一些常见错误。它们也提供一些命名文件和class的建议。

例如BEM
BEM建议使用一种特殊格式的class name:'block,element,modifier'。BEM建议永远不要使用嵌套选择器。

// BEM says bad 
.form .button {
  background-color: blue;
}
 
// BEM says good! 
.form__button {
  background-color: blue;
}

类型二:预处理

css预处理器将非css语言转换为css语言。
大部分的css预处理器的语法都与css类似,或者说是它的扩展。
预处理器的目的是为了提供更多特性的语言支持,或者更可读,或者代码更简洁。

例如SCSS

/* input: scss */
$fur: orange;
.cat {
  background-color: $fur;
 
  .paws {
    color: white;
  }
}
 
/* output: css */
.cat {
  background-color: orange;
}
.cat .paws {
  color: white;
}

类型三:后处理器

例如Autoprefixer

/* input: no vendor prefixes */
.box {
  display: flex;
}

/* output: vendor prefixes added */
.box {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex
}

类型四:内联样式辅助

内联样式的优点:

  • 不需要选择器

  • 避免冲突

  • 不依赖顺序

  • 无用代码移除

  • 表现力强

例如radium

// import React from 'react';
// import ReactDOM from 'react-dom';
// import Radium from 'radium';

class Alert extends React.Component {
  getStyles() {
    const status = {
      notification: "#0074D9",
      success: "#27AE60",
      error: "#E74C3C"
    }

    return {
      alert: {
        position: "relative",
        width: "100%",
        padding: "5px",
        borderRadius: "3px",
        backgroundColor: status.notification,
        color: "white",
        textAlign: "center",
        fontFamily: "'Helvetica Neue', sans-serif",
        success: {
          backgroundColor: status.success
        },
        error: {
          backgroundColor: status.error
        }
      },
      closeButton: {
        position: "absolute",
        right: "10px",
        color: color(status[this.props.type]).lighten(0.2).hexString(),
        ":hover": {
          color: color(status[this.props.type]).lighten(0.5).hexString(),
          cursor: "pointer"
        }
      }
    };
  }
  render() {
    const styles = this.getStyles();
    const { type, message } = this.props;
    return (
      <div style={[styles.alert, styles.alert[type]]}>
        { message }
        <span style={styles.closeButton}>&#x2715;</span>
      </div>
    );
  }
}

Alert.defaultProps = { type: "notification" };

const Component = Radium(Alert);

ReactDOM.render(<Component message="This is an alert component" />, mountNode);

参考链接:how-to-style-react