简体   繁体   English

gatsby.js 中简单 if 条件的语法是什么

[英]What is the syntax for a simple if conditional in gatsby.js

I've been combing through docs and I can't seem to find a simple example of a conditional in gatsby that is NOT a renderer condition.我一直在梳理文档,但似乎无法在 gatsby 中找到一个不是渲染器条件的简单条件示例。

I'm looking to compare within a mapped object, which is handled in the render method: (basic pseudo code)我希望在渲染方法中处理的映射对象中进行比较:(基本伪代码)

class someTemplate extends Component {
  render() {
    const someobject = this.props.data.someobject

    return (
      <div id="page-wrapper">
        {someobject.map((layout, i) => {
            return (
            <div className={(i === 0 ? (`slideshow-item shown`) : (`slideshow-item`) )}>

                {if(i === 1)} 
                    show something 
                {else if(i === 2)} 
                    show something else 
                {else} 
                    show default 
                {/if}

            </div>
            )
          })
        }
      </div>
    )
  }
}

So the ternary you see for the className works fine.所以你看到的 className 的三元工作正常。 But as an example I may have 15 items in the loop and I want to make sure I set classes for the first 3 items, for example.但作为一个例子,我可能在循环中有 15 个项目,并且我想确保我为前 3 个项目设置类,例如。 In my findings, I see a lot of people giving examples of conditional rendering outside the return statement, but I do not want to make the whole chunk of code conditional for a few simple classes.在我的发现中,我看到很多人在 return 语句之外给出了条件渲染的示例,但我不想让整个代码块成为几个简单类的条件。

Is this possible in gatsby.js or do I really need to break things apart into components to achieve something so simple?这在 gatsby.js 中是可能的,还是我真的需要将事情分解成组件来实现如此简单的事情?

Such conditions don't have anything to do with Gatsby itself.这样的条件与盖茨比本身没有任何关系。 You are now in the JSX syntax world.您现在已进入JSX 语法世界。 You can write them like this:你可以这样写:

<div className={i === 0 ? `slideshow-item shown` : `slideshow-item`}>
  {i === 1 && <span>show something</span>}
  {i === 2 && <span>show something else</span>}
  {i > 2 && <span>show default</span>}
</div>

Also note that you need to return a node - thus the <span> element in the above example (it could be any other valid node).另请注意,您需要返回一个节点 - 因此上面示例中的<span>元素(它可以是任何其他有效节点)。

EDIT: Instead of <span> element a React.Fragment can be used to avoid extra DOM elements:编辑:代替<span>元素,可以使用React.Fragment来避免额外的 DOM 元素:

{i === 1 && <>show something</>}

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

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