【问题标题】:Multiple Conditons in ternary operator React Native三元运算符 React Native 中的多个条件
【发布时间】:2021-11-20 11:30:49
【问题描述】:

大家好,我在 javascript 中使用三元运算符有两个条件。

这是我的代码,它基本上告诉一个按钮被禁用或启用:

disabled={(props.isAllowedState && (props.zkub == " " || props.zkub == "B")) || (!props.zkub == " " || !props.zkub == "B") ? false : true}

我也试过这样:

disabled={(props.isAllowedState && (props.zkub == " " || props.zkub == "B")) ? false : (!props.zkub == " " || !props.zkub == "B") ? false : true}

但它不起作用,当我分别采用条件并测试它们时它可以工作但它们一起不起作用。

也许有人可以告诉我如何解决这个问题。

褪色

编辑:我的 If 方法

  const checkDisableButton = () => {                                                 
    if(props.isAllowedState && (props.zkub == " " || props.zkub == "B")) {
      return false 
    } if (!props.zkub == " " || !props.zkub == "B") {
      return false
    } else {
      return true
    }
  };

电话:

disabled={() => checkDisableButton()}

【问题讨论】:

  • if statement 的可读性更强。
  • 为什么要分配布尔条件真值?您可以将其设置为一个条件,而无需 truefalse
  • @Andy 是的,我也试过了,但我的结果不是我预期的 - 也许我做错了,所以如果你能告诉我你的方法,我会调查它 - 我会编辑我的问题并显示我的 if 函数
  • @rm-fme 你到底是什么意思?
  • @yesIamFaded,让我理解一下要求:如果 isAllowedState == true 并且 zkub 为空或等于 B,它会返回 False?

标签: javascript reactjs react-native conditional-operator


【解决方案1】:

我会创建一个isDisabled 函数,它使用 if 语句而不是复杂的三元。

function isDisabled() {

  const { isAllowedState, zkub } = props;

  if (isAllowedState && (zkub === ' ' || zkub === 'B')) return false;
  if (zkub !== ' ' || zkub !== 'B') return false;
  return true;

}

然后调用它:

disabled={isDisabled()}

【讨论】:

    猜你喜欢
    • 2021-01-28
    • 2019-02-17
    • 1970-01-01
    • 2012-09-14
    • 2011-06-26
    • 2013-01-14
    • 2013-06-06
    • 2018-03-06
    • 2015-08-29
    相关资源
    最近更新 更多