How can I write an else if structure using React (JSX) - the ternary is not expressive enough

前端 未结 6 1710
情话喂你
情话喂你 2021-01-01 18:47

I want to write the equivalent in react:

if (this.props.conditionA) {
    Condition A
} else if (this.props.conditionB) {
    

        
6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-01 19:19

    If your condition is as simple as what you expressed, I think you can still use ternary as @SkinnyJ mentioned above. It's quite elegant, but I get your concern if there are lot of these conditions to check. There's one other way to solve this problem: using switch statement.

    const props = {
      conditionA: "this is condition a"
    };
    
    let value;
    
    switch (Object.keys(props)[0]) {
      case "conditionA":
        value = "Condition A";
        break;
      case "conditionB":
        value = "Condition B";
        break;
      default:
        value = "Neither";
    }
    
    console.log(value);
    

    There are a couple of assumptions being made here. That the object is not null and that it has only one property.

    But if those are true, for scenarios like this, switch might be more performant. This might be of interest for you:

    Javascript switch vs if else

提交回复
热议问题