使用 OR 运算符的条件渲染

Conditional rendering with OR operator

我有以下代码;

       {
          this.state.isWPAEnterpriseInstalled && !this.state.passpoint && !this.state.expanded || this.state.isWPAEnterpriseInstalled && !this.state.expanded && this.state.isEnterprise && <TouchableOpacity style={!this.state.expanded ? [styles.button, { backgroundColor: this.state.primary_color }] : [styles.expandedButton, { backgroundColor: this.state.primary_color }]}
            activeOpacity={0} onPress={this.removeConfigEnterprise}>
            <Text allowFontScaling={false} style={styles.button_text}>Remove WPA </Text>
          </TouchableOpacity>
        }

我遇到的问题是条件渲染线;

this.state.isWPAEnterpriseInstalled && !this.state.passpoint && !this.state.expanded || this.state.isWPAEnterpriseInstalled && !this.state.expanded && this.state.isEnterprise &&

好像它只识别 OR 运算符之间的这些条件之一,即先放置的那个。 OR (||) 运算符是否可能在具有条件渲染的 React 中不可用?

如果是这样,我怎样才能实现以下目标?例如基于 2 OR 条件渲染。

IF ABC AND GH AND ER OR DEF AND FGH AND TYU then display button

编辑

已解决。上面的代码有效,但在我期望不同值的状态集之一中存在不匹配。

我不确定我是否正确理解了你的问题,如果我错了请告诉我,但我认为你缺少括号。 我认为您正在尝试渲染 this.state.isWPAEnterpriseInstalled

也许您打算写以下内容:

(this.state.isWPAEnterpriseInstalled && !this.state.passpoint && !this.state.expanded) || (this.state.isWPAEnterpriseInstalled && !this.state.expanded && this.state.isEnterprise) && <TouchableOpacity>...

希望能帮到你

Is it possible that the OR (||) operator is not available in React with conditional rendering?

不,JSX 应该接受任何 JavaScript 表达式。

If so, how can I achieve the below? e.g. render based on 2 OR condition.

IF ABC AND GH AND ER OR DEF AND FGH AND TYU then display button

这里解释了 && shorthand 用于条件渲染的方式: https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator

之所以有效,是因为 true && VALUE 总是 returns VALUE,在本例中是要渲染的元素。

但是当我们在两者之间添加一个 OR 运算符时,它 returns 布尔值而不是元素。

要解决此问题,您需要将整个语句括在括号中。

并且您可能需要考虑使用内联 if-else 语句,因为在将此技术与非布尔值(ex - 字符串)一起使用时,react-native can crash 由于文本在 [=14 之外呈现=] 元素.