Understanding the usage of clsx in React

这一生的挚爱 提交于 2020-07-17 07:23:46

问题


I am trying to understand some uses of clsx in assigning classnames to a component in React.

The construct

className={clsx(classes.menuButton, open && classes.hide)} 

is clear enough. It applies 'classes.menuButton', and also applies 'classes.hide' if the value of the boolean 'open' is true.

My question relates to this second example:

className={clsx(classes.appBar, {[classes.appBarShift]: open })}

This will apply 'classes.appBar'. But what is the meaning of the second parameter?


回答1:


This is used for when you have an array of dynamic classNames (using jss for example). It means that some class will only be applied if a given condition evaluates to true

const menuStyle = clsx({
    [classes.root] : true, //always apply
    [classes.menuOpen] : open //only when open === true
})

In this example [classes.menuOpen] (which will evaluate to something like randomclassName123) will only be applied if open === true


clsx basically performs a string interpolation so you don't have to necessarily use it to conditionally apply classes. There are many supported syntax that you can check in the official docs

Instead of

<div className={`${classes.foo} ${classes.bar}, ${classes.baz}`} />

You can use it like

const { foo, bar, baz } = classes
const style = clsx(foo, bar, baz)

return <div className={style} />



回答2:


classes.appBarShift will be applied only if open evaluates to true. If the array has more classes all of them will be applied if open evaluates to true



来源:https://stackoverflow.com/questions/57557271/understanding-the-usage-of-clsx-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!