了解React中clsx的用法 [英] Understanding the usage of clsx in React

查看:2952
本文介绍了了解React中clsx的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解clsx在为React中的组件分配类名时的一些用法.

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

构造

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

很清楚.它会应用'classes.menuButton',如果布尔值'open'的值为true,也会应用'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 })}

这将应用"classes.appBar".但是第二个参数是什么意思?

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

推荐答案

这用于具有动态classNames数组(例如,使用jss)的情况.这意味着只有在给定条件计算为true

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
})

在此示例中,[classes.menuOpen](其结果将类似于randomclassName123)仅在open === true

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

clsx基本上执行string插值,因此您不一定必须使用它来有条件地应用类.您可以在官方文档

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

代替

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

您可以像使用它

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

return <div className={style} />

这篇关于了解React中clsx的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆