在gatsby jsx中添加`if`条件。

问题描述 投票:0回答:2

我想在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
2个回答
2
投票
 <p>{isPinned && <span>This is PINNED item</span>}</p>

如果 isPinned 评价为 true,而且由于 <span /> 是真理性的,那么整个表达式的值将是这样的。span因此,你想要的结果。


1
投票

你应该使用条件渲染。修改你的代码。

// 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>
© www.soinside.com 2019 - 2024. All rights reserved.