【问题标题】:JS React short circuit for onpressJS React onpress 短路
【发布时间】:2021-03-18 08:08:03
【问题描述】:

如果参数 isEnabled === false,我想禁用“onPress”,

像这样工作:

const RightTitle = ({children, onPress, isEnabled}) => (
  <Right
    onPress={isEnabled === true ? onPress : console.log("chuchas")}
    isEnabled={isEnabled}>
    <CTALight>{children}</CTALight>
  </Right>
)

但是如果我做一个“短路”来避免三元我得到一个错误

onPress 不是函数

const RightTitle = ({children, onPress, isEnabled}) => (
  <Right
    onPress={isEnabled && {onPress}  }
    isEnabled={isEnabled}>
    <CTALight>{children}</CTALight>
  </Right>
)

编辑:如果“onPress”没有括号,同样的问题

onPress={isEnabled && onPress  }

如何评估我的“isEnabled”以允许按钮 onPress?

提前致谢。

【问题讨论】:

  • 只需省略 { } 周围的 onPress: onPress={isEnabled &amp;&amp; onPress}
  • 感谢@Samathingamajig 没有括号的同样问题
  • onPress={isEnabled ? onPress : undefined}
  • 如果它在那之后给你问题,问题在于你的组件 Right 在 onPress 未定义时实际上没有处理逻辑。

标签: javascript reactjs conditional-operator


【解决方案1】:

你的onPress 应该有一个可以调用的函数。在isEnabledfalsy 的情况下,你将得到那个虚假的值作为回报(例如:如果它是false,你会得到false,这不是一个函数)。您可以将调用包装在自己的函数中,如果它是虚假的,它将返回 isEnabled,或者调用您的 onPress 处理程序:

onPress={() => isEnabled && onPress()}

【讨论】:

    【解决方案2】:

    如果使用逻辑 AND (&amp;&amp;),那么您需要检查孩子的 onPress 回调是否有效。 falseundefined 不是函数,不能作为一个函数调用。

    onPress={isEnabled && onPress}
    

    右子组件

    onPress && onPress()
    

    onPress?.()
    

    或者,您只需要提供一个 NOOP 函数,Right 组件可以调用而无需先检查。

    onPress={isEnabled ? onPress : () => {}}
    

    【讨论】:

      【解决方案3】:

      如果isEnabled 为假,则 onPress === false,这不是一个函数。您需要在末尾附加一个空函数才能使其正常工作。

      onPress={isEnabled &amp;&amp; onPress || (() =&gt; {})}

      isEnabled = true;
      onPress = () => console.log("press");
      
      console.log(typeof (isEnabled && onPress));
      console.log(typeof (isEnabled && onPress || (()=>{})));
      
      isEnabled = false;
      
      console.log(typeof (isEnabled && onPress));
      console.log(typeof (isEnabled && onPress || (()=>{})));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-11
        • 1970-01-01
        • 2020-05-30
        • 2017-12-23
        • 2017-09-01
        • 2016-11-08
        • 2021-01-30
        • 1970-01-01
        相关资源
        最近更新 更多