【问题标题】:conditional className ternary operator rendering条件类名三元运算符渲染
【发布时间】:2021-06-01 10:05:44
【问题描述】:

我有一个带有条件 className 样式的 div。

<div className={type === "myType" && classes.myClass}>

所以如果类型是myType,我想申请myClass。但是如果类型不是myType 我会收到警告:

Warning: Received `false` for a non-boolean attribute `className`.

If you want to write it to the DOM, pass a string instead: className="false" or className={value.toString()}.

If you used to conditionally omit it with className={condition && value}, pass className={condition ? value : undefined} instead.
    at div

在那种情况下,我通常会这样替换我的条件:

<div className={type === "myType" ? classes.myClass : null}>

但警告建议我使用undefined 而不是null

所以我想问什么更好用,为什么?

【问题讨论】:

  • A && B 将返回 A 如果 A 是假的,并且 false 不是 className 的有效值。 null 显然也不是。

标签: javascript reactjs


【解决方案1】:

我认为最好的方法都不是,因为类名是一个字符串,所以最好的做法是返回相同类型的数据。

代码如下: <div className={type === "myType" ? classes.myClass : ""}>

【讨论】:

  • 值可以是未定义的,但字符串不能。 "" 不是未定义的。
  • 真的,用词不当,在整个段落中,我的意思是“”是假的,而非空字符串是真的。
【解决方案2】:

你应该使用clsx之类的东西。

这比警告建议的本机解决方案要干净得多,clsx 允许您执行以下操作:

import clsx from 'clsx';
 
// Strings (variadic)
clsx('foo', true && 'bar', 'baz');
//=> 'foo bar baz'
 
// Objects
clsx({ foo:true, bar:false, baz:isTrue() });
//=> 'foo baz'
 
// Objects (variadic)
clsx({ foo:true }, { bar:false }, null, { '--foobar':'hello' });
//=> 'foo --foobar'
 
// Arrays
clsx(['foo', 0, false, 'bar']);
//=> 'foo bar'
 
// Arrays (variadic)
clsx(['foo'], ['', 0, false, 'bar'], [['baz', [['hello'], 'there']]]);
//=> 'foo bar baz hello there'
 
// Kitchen sink (with nesting)
clsx('foo', [1 && 'bar', { baz:false, bat:null }, ['hello', ['world']]], 'cya');
//=> 'foo bar hello world cya'

【讨论】:

  • 不确定这样的简单案例是否需要整个库...
  • @Alex 这个库只有一个功能,而且非常小(40 行)。 Yana 没有向我们展示整个项目,但我怀疑任何现实的项目都会有多个类名和附加条件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多