react之只用classNames避免字符串拼接


之前在react當中使用了字符串拼接的方式來拼接類名的字符串,這種方法不僅不夠方便,還會出現很多問題

使用classNames這個工具,可以省去拼接字符串的煩惱,大大提高開發效率

首先,最簡單的使用方法

import classNames from "classnames"
classNames('foo', 'bar'); // => 'foo bar'

復雜的使用

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' 

同時還可以和es6的模板字符串使用更加簡單

let faStyle = "home";

classNames("fa",`fa-${faStyle}`) // => "fa fa-home"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM