繁体   English   中英

根据 Astro 组件中的数据 json 隐藏或显示 div

[英]Hide or show div according data json in Astro's component

我的项目中有 site.json 有很多数据字符串。 如何根据 JSON 数据读取 json 文件并隐藏或显示特定 div? 由于我为其创建组件的项目并不都包含对 githab 的引用或具有域名,因此我只需要向在 json 中具有此类链接的项目显示 svg。

项目.astro:

---
import ProjectItem from './ProjectItem.astro';
import site from "../data/site.json";
const title = `Projects I’ve been working on`;
const {projects} = site;
---
<section id="projects">
    <h3>{title}</h3>
        {projects.map((item) => (
            <ProjectItem item={item} />
        ))}
</section>

在 ProjectItem.astro 中,请注意“div class="external",其中为外部链接和项目的 github 创建了两个链接。如果在 site.json 中有我的每个项目的特定信息,我想创建它们。现在这些链接已创建无论如何,有没有关于 githab 或域名的信息。我试图在 javascript 中编写一个脚本,但我做不到。

'ProjectItem.astro':

---
const { item } = Astro.props;
---
<div class="project-item-grid">
    <div class="project-item-right">
        <div class="external">
            <a href={item.link} class="link">
                <img src="assets/external_link_100.svg" />
            </a>
            <a href={item.github} class="link">
                <img src="assets/github_100.png" />
            </a>
        </div>
    </div>
</div>

这是我的网站。json。 我把它变小了,因为它很大。 但请注意“项目”,尤其是项目->链接和项目->github。

{
"skills": {
      "comfortable": [
            {...}],
      "familiar": [
            {...}],
},
"projects": [
      {
        "title": "Title1",
        "link": "link1.com",
        "github": "link1.github.io"
      },
      {
        "title": "Title2",
        "link": "link2.com",
        "github":             // information is absent. I think you can put null or "" instead an empty field.
      },
        "title": "Title3",
        "link": ,             // now link's information is absent.
        "github": "link3.github.io"           
      },
... etc.
]}

在那里,我尝试用 JS 自己解决问题:

const file = require('../data/site.json');
try {
      const data = JSON.parse(file)
     } catch(err) {
         console.error(err)
     }
for (let i=0; i < 3; i++) {
        if (data.projects[i].github === null) {
            document.getElementById('github').style.display = 'none'
            console.log("Catch!");
        } else {
            console.log("No catch");
        }
    }

试试这个:

只是使用三元运算符隐藏 null 或未定义的值。

---
const { item } = Astro.props;
---
<div class="project-item-grid">
    <div class="project-item-right">
        <div class="external">
            <a style={item.link? ' ':'display:none'} href={item.link} class="link"> 
                <img src="assets/external_link_100.svg" />
            </a>
            <a style={item.github? ' ':'display:none'} href={item.github} class="link">
                <img src="assets/github_100.png" />
            </a>
        </div>
    </div>
</div>

暂无
暂无

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

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