欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

React中classnames庫使用示例

 更新時(shí)間:2022年10月28日 09:55:53   作者:QiShare  
這篇文章主要為大家介紹了React中classnames庫使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

classnames的引入

從名字上可以看出,這個(gè)庫是和類名有關(guān)的。官方的介紹就是一個(gè)簡單的支持動態(tài)多類名的工具庫。

支持使用 npm, Bower, or Yarn

使用 npm安裝

npm install classnames

使用 Bower安裝

bower install classnames

使用 Yarn安裝

yarn add classnames

引入

import classnames from ‘classnames';

使用 Node.js, Browserify, or webpack:

Node.js, Browserify, webpack:

var classNames = require('classnames');
classNames('foo', 'bar'); // => 'foo bar'

classnames函數(shù)的使用

classNames 函數(shù)接受任意數(shù)量的參數(shù),可以是string、boolean、number、array、dictionary等。

type ClassValue = string I number I ClassDictionary I ClassArray I undef inednull I boolean;

參數(shù) 'foo' 是 { foo: true } 的縮寫。如果與給定鍵關(guān)聯(lián)的值是false的,則該key值將不會包含在輸出中。

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'

數(shù)組的形式

數(shù)組可以按照上面的規(guī)則,遞歸展開數(shù)組中的每一項(xiàng):

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

ES6中使用動態(tài)類名

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

結(jié)合React一起使用

這個(gè)包是classSet的官方替代品,她最初是在React.js插件包中提供的。

常見的一個(gè)應(yīng)用場景是根據(jù)條件動態(tài)設(shè)置類名,在React中是會寫出如下的代碼:

class Button extends React.Component {
// ...
render () {
var 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可以通過對象非常方便的寫出條件多類名。

var classNames = require('classnames');
class Button extends React.Component {
// ...
render () {
    var 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>;
}
}

因?yàn)榭梢詫ο蟆?shù)組和字符串參數(shù)混合在一起,所以支持可選的 className props 也更簡單,因?yàn)橹挥姓鎸?shí)的參數(shù)才會包含在結(jié)果中:

var btnClass = classNames('btn', this.props.className, {
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});

總結(jié):

在React項(xiàng)目中使用classnames是非常方便我們管理動態(tài)多類名。為我們的工作真正的提效。

以上就是React中classnames庫使用示例的詳細(xì)內(nèi)容,更多關(guān)于React classnames庫的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論