【问题标题】:Add `if` condition in gatsby jsx在 gatsby jsx 中添加 `if` 条件
【发布时间】:2020-09-20 13:59:30
【问题描述】:

在某些情况下,我想在 gatsby 模板文件中添加元素。

我正在使用 gatsby 开发文档站点,该文档由 markdown 文件制作。 这是 md 文件和 gatsby 模板。如果文档有 pinned=true 条件,如何添加元素??

降价

---
title: "doc title"
date: "2020-06-01"
tags: ["some","tags"]
pinned: TRUE
---

document body.

模板文件

import React from "react"
import { graphql } from "gatsby"

export default class DocsList extends React.Component {
  render() {
    const posts = this.props.data.allMarkdownRemark.edges
    return (
    <div>
      {posts.map(({ node }) => {
        const title = node.frontmatter.title || node.fields.slug
        const tags = node.frontmatter.tags || node.fields.slug
        const ispinned = node.frontmatter.pinned || node.fields.slug
        return(
        <p>{title}</p>
        <p>{(tags || []).map(tags => (<span className="tags" key={tags}><FaHashtag />{tags}</span>))}</p>

        // if the document has `pinned=true` attribute, show <span> tag below
        <p>{if {ispinned===true ? `<span>This is PINNED item</span>` }}</p>
        )
        })}
    </div>
        )
    }
}

export const query = graphql`
query docssListQuery($skip: Int!, $limit: Int!) {
  allMarkdownRemark(
    filter: {
      fields: { collection: { eq: "manuals" } }
      frontmatter: { published: { ne: false } }
    }
    sort: { fields: [frontmatter___date], order: DESC }
    limit: $limit
    skip: $skip
  ) {
    edges {
      node {
        id
        fields {
          slug
        }
        frontmatter {
          title
          date
          tags
          pinned
        }
        excerpt
        timeToRead
      }
    }
  }
}
`;

【问题讨论】:

标签: reactjs markdown jsx gatsby


【解决方案1】:
 <p>{isPinned && <span>This is PINNED item</span>}</p>

如果isPinned 的计算结果为true,并且由于&lt;span /&gt; 是真值,那么整个表达式的值就是span,因此是您想要的结果。

【讨论】:

  • 感谢您的快速答复。我应用了这个,但是 显示在每个文档上。我有两个 md 文档,其中有 pinned 属性 true 和 false。并且 graphql 结果正在集体响应。
  • 我试过console.log(isPinned),结果如下 --- /manuals/faq/
【解决方案2】:

您应该使用条件渲染。更改您的代码:

// if the document has `pinned=true` attribute, show <span> tag below
<p>{if {ispinned===true ? `<span>This is PINNED item</span>` }}</p>

// if the document has `pinned=true` attribute, show <span> tag below
<p>{ispinned ? `<span>This is PINNED item</span>`: null }</p>

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多