react系列知识---09样式处理

799 阅读1分钟
  • 基本样式设置

    • 行内样式:设置行内样式时要使用对象

      const style = {
          color: 'white',
          backgroundImage: `url(${imgUrl})`,
          // 注意这里大写的 W,会转换成 -webkit-transition
          WebkitTransition: 'all',
          // ms 是唯一小写的浏览器前缀
          msTransition: 'all'
      };
      const component = <Component style={style}/>;
      
    • 自定义样式

      设置 className prop

注意:

  1. 样式中的像素值

当设置 width 和 height 这类与大小有关的样式时,大部分会以像素为单位,此时若重复输 入 px ,会很麻烦。为了提高效率,React 会自动对这样的属性添加 px 。比如:

// 渲染成 height: 10px
const style = { height: 10 };
ReactDOM.render(<Component style={style}>Hello</Component>, mountNode);

注意,有些属性除了支持 px 为单位的像素值,还支持数字直接作为值,此时 React 并不添 加 px ,如 lineHeight

  1. 使用 classnames 库

可以使用 classnames 库来操作类

如果不使用 classnames 库,就需要这样处理动态类名:

import React, {Component} from 'react';
class Button extends Component {
    // ...
    render() {
        let btnClass = 'btn';
        if (this.state.isPressed) {
            btnClass += ' btn-pressed';
        } else if (this.state.isHovered) {
            btnClass += ' btn-over';
        }
        return <button className={btnClass}>{this.props.label}</button>;
    }
};

使用了 classnames 库代码后,就可以变得很简单:

import React, {Component} from 'react';
import classNames from 'classnames';
class Button extends Component {
    // ...
    render() {
        const btnClass = classNames({
            'btn': true,
            'btn-pressed': this.state.isPressed,
            'btn-over': !this.state.isPressed && this.state.isHovered
        });
        return <button className={btnClass}>{this.props.label}</button>;
    }
});
  • CSS Modules

    • Sass、Less、PostCSS 等试图解决 CSS 编程能力弱的问题,但这并没有解决模块化这个问题

    • CSS Modules 模块化方案

      结合 webpack 的 css-loader,就可以在 CSS 中定义样式,在 JavaScript 文件中导入

  • class 命名技巧

CSS Modules 的命名规范是从 BEM 扩展而来的。BEM 把样式名分为 3 个级别,具体如下 所示。

  • Block:对应模块名,如 Dialog。
  • Element:对应模块中的节点名 Confirm Button。
  • Modifier:对应节点相关的状态,如 disabled 和 highlight。

BEM 最终得到的 class 名为 dialog__confirm-button--highlight 。使用双符号 __ 和 -- 是为 了与区块内单词间的分隔符区分开来。虽然看起来有些奇特,但 BEM 被非常多的大型项目采用。 CSS Modules 中 CSS 文件名恰好对应 Block 名,只需要再考虑 Element 和 Modifier 即可。BEM 对应到 CSS Modules 的做法是:

/* .dialog.css */
.ConfirmButton--disabled {}

我们也可以不遵循完整的命名规范,使用小驼峰的写法把 Block 和 Modifier 放到一起:

/* .dialog.css */
.disabledConfirmButton {}
  • 实现 CSS 与 JavaScript 变量共享
/* config.scss */
$primary-color: #f40;
:export {
primaryColor: $primary-color;
}
/* app.js */
import style from 'config.scss';
// 会输出 #F40
console.log(style.primaryColor);