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

本文详细介绍了在React中如何高效地设置和使用样式,包括行内样式、自定义样式、使用classnames库以及CSS Modules的技巧,同时讲解了如何在CSS和JavaScript间共享变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 基本样式设置

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

      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);
复制代码

转载于:https://juejin.im/post/5c24798bf265da614171a052

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值