简体   繁体   English

如果没有模板字符串且没有条件(三元)运算符,但带有if-else,此React代码的外观如何?

[英]How would this React code look like without a template string and without a conditional (ternary) operator, but with if-else?

How would this React code look like without a template string and without a conditional (ternary) operator, but with if-else?" I read the documentation, but I want to visually see the example on my code, and not on someone else's code. 如果没有模板字符串且没有条件(三元)运算符,但具有if-else,此React代码的外观如何?”我阅读了文档,但我想直观地在我的代码上看到该示例,而不是在别人的代码上看到该示例。

<button className={`tablinks ${i === active ? 'active' : ''}`}
            onClick={openTab}
            data-index={i}
>{n.title}</button>

Well you can could define the if-else logic outside the markup. 好吧,您可以在标记之外定义if-else逻辑。 You would define it in the .map() , before returning the markup. 您可以在返回标记之前在.map()定义它。 Makes it cleaner. 使它更清洁。

.map(i){
   ...
   let classes = "tablinks"
   if(i === active){
      classes = classes + " active"
   }

   return(
       <button 
           className={classes}
           onClick={openTab}
           data-index={i}
        >
         {n.title}
      </button>
   )
}

The inside of the JSX {} s needs to be an expression, and if / else alone cannot be used in an expression context - you'll need an IIFE (or a separate named function that you invoke, or a variable name defined beforehand) instead: 的JSX内部{}的需求是一个表达式, if / else不能单独在表达式上下文中使用-你需要一个IIFE(或者你调用一个单独的命名函数,或预先定义的变量名)代替:

<button
  className={
    (() => {
      if (i === active) {
        return 'tablinks active';
      } else {
        return 'tablinks';
      }
    })()
  }
  onClick={openTab}
  data-index={i}
>{n.title}</button>

It's a lot uglier, and introduces a lot of syntax noise. 这很丑陋,并且引入了很多语法噪音。 I wouldn't recommend it. 我不推荐它。

The conditional operator here is pretty helpful, but the template literal isn't as useful - if you wanted to just remove the template literal, it would look like 这里的条件运算符很有帮助,但是模板文字并没有那么有用-如果您只想删除模板文字,它看起来像

<button
  className={'tablinks ' + (i === active ? 'active' : '')`}
  onClick={openTab}
  data-index={i}
>{n.title}</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM