三元运算符(如果没有其他则为内联) [英] Ternary Operator (Inline If without Else)

查看:136
本文介绍了三元运算符(如果没有其他则为内联)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在<form>中有两个checkbox. <form>分配有一个onChange={this.checkBoxOnChange},它会在表单中的每次更改时启动checkBoxOnChange(event){..}功能.我正在尝试将(Log)状态映射为(即是否选中了它们).因此,我最初将那里的值称为false,因为未对其进行检查,然后在每次事件中我都尝试分别更改那里的值(即,如果为false,则为真,反之亦然) .

I have two checkbox in a <form>. The <form> have an onChange={this.checkBoxOnChange} assigned to it which fires up checkBoxOnChange(event){..} function on every change in the form. I am trying to map (Log) the status (ie whether they are checked or not). So, I've initially taken there value as false as they are not-checked then on each event I'm trying to change there value respectively (ie if false the true & vice versa).

遵循因此,我尝试了此操作:

On following this SO post I tried this:

(event.target.value=='BILLDED') && billed=(!billed)       

这样做,我得到:

语法错误:赋值表达式中的左侧无效

Syntax error: Invalid left-hand side in assignment expression

然后我尝试了这个:

(event.target.value=='BILLDED') ? (billed=(!billed)) : null        

但是,它在每个onChange上给了我BILLED:true(单击BILLED checkbox时)
这是渲染方法中复选框的代码:

However, it gives me BILLED:true on every onChange (when clicked on BILLED checkbox)
This is code for checkbox inside render method:

render() {
    return (
      <div>
      <form onChange={this.checkBoxOnChange}>
        <input type="checkbox" name="invoicestatus" value="BILLDED" />BILLDED<br />
        <input type="checkbox" name="invoicestatus" value="PENDING" />PENDING<br />
      </form>
      <ListData data={this.state.data}/>
    </div>
    );
  }

这是同一类(组件)中的checkBoxOnChange()函数:

This is the checkBoxOnChange() function within that same class (Component):

   checkBoxOnChange(event){
    var billed=false;
    var pending=false;
  //  (event.target.value=='BILLDED') ? (billed=(!billed)) : null;
    (event.target.value=='BILLDED') && billed=(!billed)
  //  (event.target.value=='PENDING') ? pending=(!pending) : null;
    console.log("BILLDED:"+billed+"  PENDING:"+pending);
  }

  • 代码有什么问题?
  • 在这种情况下我不能使用内联语句吗?
  • 有没有更好,更简洁的方法?
  • 推荐答案

    代码有什么问题?

    What's wrong with the code?

    您将事件处理程序内的billed变量初始化为false,这就是为什么总是获得true而不是切换状态的原因.

    You initialise the billed variable inside your event handler to false, that's why you always get true instead of toggling a state.

    在这种情况下我不能使用内联语句吗?

    Can I not use inline statement for this scenario?

    您可以,只需将括号放在正确的位置即可.

    You can, you just have to put the parenthesis in the right place:

    (event.target.value == 'BILLDED') && (billed = !billed);
    //                                   ^
    

    有没有更好,更简洁的方法?

    Is there any better, more concise approach?

    使用普通的if语句.它既短又可读:

    Use a normal if statement. It's both shorter and more readable:

    if (event.target.value == 'BILLDED') billed = !billed;
    

    这篇关于三元运算符(如果没有其他则为内联)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆