在三元运算符中使用 OR

Using OR in ternary operator

我有一个简单的三元运算符,我想用两个不同的字符串 return null。

this.props.sportType === 'tennis' || 'soccer' ? null : <li onClick={this.props.onClick} className={styles.menuItem}>N/A</li>

但不幸的是,这并不完全有效。我怎样才能使用 ||在三元运算符中正确吗?

谢谢! :)

使用一个数组,看是否包含sportType

['tennis', 'soccer'].includes(this.props.sportType)
? null
: <li onClick={this.props.onClick} className={styles.menuItem}>Sport</li>

(另外,最好缩进较长的表达式)

重复与第二个值的比较

this.props.sportType === 'tennis' || this.props.sportType === 'soccer'
    ? ...

如同在 IF 语句中一样,您需要将 "soccer" 字符串与

进行比较
this.props.sportType === 'tennis' || this.props.sportType === 'soccer' ? null : <li onClick={this.props.onClick} className={styles.menuItem}>N/A</li>

您可以使用正则表达式

/^tennis|soccer$/.test(this.props.sportType) ? null : <li onClick={this.props.onClick} className={styles.menuItem}>N/A</li>