【源码共读】经常用的 classNames,你知道是怎么实现的么

1. 前言

今天来学习以下 classnames 的源码,这个库应该 react 的开发者都有用过,这两者联系可谓是非常紧密,配合使用相当方便

1.1 你能学到

  1. classnames 的用法
  2. classnames 的原理
  3. classnames 中的测试

2. 看代码之前

先从 README 中了解该库的相关信息

2.1 了解该库的用途

A simple JavaScript utility for conditionally joining classNames together.

一个简单的 JavaScript 实用程序,用于有条件地将类名连接在一起。

2.2 使用方式

classNames 作为核心方法,可以接收任意数量的参数,并根据一些判断依据返回最终以空格分隔的类名串。
如果key 的值是 false 那么就不会加入到最后的字符串中

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1' 

数组传入就按扁平化后再根据判断处理:

var arr = ['b', { c: true, d: false }];
classNames('a', arr); // => 'a b c' 

这样可以结合 ES6 中的模板字符串达到动态类型的效果

let buttonType = 'primary';
classNames({ [`btn-${buttonType}`]: true }); 

react + classNames

在 react 组件中,就可以将其设置为 state,通过绑定事件的回调函数对其进行更改,使其类名动态更改、样式动态更改的效果

class Button extends React.Component {
  // ...
  render () {
    var btnClass = 'btn';
    if (this.state.isPressed) btnClass += ' btn-pressed';
    else if (this.state.isHovered) btnClass += '
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值