如何在 React 中使用 clsx [英] How to use clsx in React

查看:142
本文介绍了如何在 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"的值为真,它也会应用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?

推荐答案

clsx 通常用于有条件地应用给定的 className

clsx is generally used to conditionally apply a given className

这种语法意味着只有在给定条件的计算结果为 true

This syntax means that some class will only be applied if a given condition evaluates to true

const menuStyle = clsx({
    [classes.root] : true, //always applies
    [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 基本上输出一个 字符串插值.因此,尽管这是一种常见做法,但您不一定非要使用它.

clsx basically outputs a string interpolation. So you don't have to necessarily use it although is a common practice.

有许多支持的语法,您可以在官方文档

代替

There are many supported syntax that you can check in the official docs

Instead of

你可以这样使用

You can use it like this

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

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