三元运算符(内联 If 没有 Else)

Ternary Operator (Inline If without Else)

我在 <form> 中有两个 checkbox<form> 有一个 onChange={this.checkBoxOnChange} 分配给它,它会在表单中的每次更改时触发 checkBoxOnChange(event){..} 函数。我正在尝试映射 (Log) 状态 (即是否检查它们)。因此,我最初将那里的价值设为 false,因为它们没有被检查,然后在每个事件中我试图分别更改那里的价值 (即如果为假则为真,反之亦然)

在关注 this SO post 我试过这个:

(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
这是渲染方法中复选框的代码:

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>
    );
  }

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

   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 而不是切换状态的原因。

Can I not use inline statement for this scenario?

可以,只要把括号放在正确的位置即可:

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

Is there any better, more concise approach?

使用正常的 if 语句。它既更短又更易读:

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

However, it gives me BILLED:true on every onChange (when clicked on BILLED checkbox)

这不是因为你使用了下面的局部变量吗

var billed=false;

始终以 false?

开头