This is the second day of my participation in the August Text Challenge.More challenges in August

One, foreword

During the youth camp project, I noticed that there was a component called classnames in the component written by the big guy, but I didn’t use it, so I immediately went to Baidu to get a general idea of how to use it and took notes.

Second, the content

1. Introduction

Classnames are an extension of the React classname attribute, since the React native doesn’t support dynamic addition of multiple classnames.

2. Use

# via npm
npm install classnames

# via Bower
bower install classnames

# or Yarn (note that it will automatically save the package to your `dependencies` in `package.json`)
yarn add classnames
Copy the code

Import when needed:

import classnames from "classnames";
Copy the code

Its primary use is to add multiple class names. Simplest usage:

import classnames from "classnames";

<div className={classnames("class1","class2")} ></div>
Copy the code

This gives you a component with two class names:

<div class="class1 class2"></div>
Copy the code

It can add class names in a variety of ways:

{ // Add class name by object}
<div className={classnames({"hot": true, },{"cold": false,"sunner"})} ></div>      { // hot sunner }
{ // Add class name by array}
<div className={classnames(["abc","def"[the],"ghi"])} ></div>      { // abc def ghi }
{ // undefined null false "" 0 will be ignored}
<div className={classNames(null, false, 'bar', undefined.0.1, { baz: null}, ' ')} ></div>    { // bar 1 }
{ // Can be put together by various combinations of class names}
<div className={classNames('a'["b"{"c": false,"d": true}])}></div>      { // a b d }
{ // The class name can be set to props and state equivalents.
<div className={classNames('btn', this.props.className{'btn-pressed': this.state.isPressed,
  'btn-over': !this.state.isPressed && this.state.isHovered})} ></div>
Copy the code

It also supports the use of bind to change Pointers

import classnames from "classnames";

let styles = {
  foo: 'abc'.bar: 'def'.baz: 'xyz'
};
let cx = classNames.bind(styles);
let className = cx('foo'['bar'] and {baz: true }); // => "abc def xyz
Copy the code

Third, summary

I think the best thing about classnames is that it can change component classnames dynamically, and it can play a lot of tricks, and it supports various types of data to add classnames. It is a great plugin.


I hope you can point out any questions in the comments section, AND I will correct them in time.

New people on the road, but also include more. I am MoonLight, a fledgling small front end.