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