How to add multiple classes to a ReactJS Component?

后端 未结 29 2277
执念已碎
执念已碎 2020-11-27 09:16

I am new to ReactJS and JSX and I am having a little problem with the code below.

I am trying to add multiple classes to the className attribute on eac

29条回答
  •  感动是毒
    2020-11-27 09:25

    Late to the party, but why use third party for such a simple problem?

    You could either do it as @Huw Davies mentioned - the best way

    1. 
    2. 

    Both are good. But writing can become complex for a large app. To make it optimal, I do the same above things but put it in a helper class

    Using my below helper function, allows me to keep the logic separate for future editing, and also gives me multiple ways to add the classes

    classNames(styles['foo-bar-baz], 'fa fa-user', 'fa-2x')
    

    or

    classNames([styles['foo-bar-baz], 'fa fa-user', 'fa-2x'])
    

    This is my helper function below. I've put it in a helper.js where I keep all my common methods. Being such a simple function, I avoided using 3rd party to keep control

    export function classNames (classes) {
        if(classes && classes.constructor === Array) {
            return classes.join(' ')
        } else if(arguments[0] !== undefined) {
            return [...arguments].join(' ')
        }
        return ''
    }
    

提交回复
热议问题