首页 > 解决方案 > 仅当通过另一个文件提供链接时如何显示按钮(React)

问题描述

我正在使用 React 和 Tailwind 开发我的个人作品集网站。只有当我通过我的 data.js 文件提供 GitHub 链接时,我才试图弄清楚如何为我的项目卡显示“GitHub”按钮。

我正在使用卡片组件和 map 方法为 data.js 中提供的每个项目显示卡片。如您所见,我没有提供第一个项目的 GitHub 链接,但我提供了第二个项目。如何让我只提供 GitHub 链接的项目出现 GitHub 按钮?

我试图创建一个函数来仅在提供 href 值但不起作用时才显示按钮。任何可以引导我走向正确方向的建议都将受到高度赞赏。

GitHub 仓库:https ://github.com/fotinh0/my-portfolio

数据.js

export const projects = [
  {
    title: "PCI Media Website",
    subtitle: "Company Website using WordPress",
    description:
      "Maintained PCI Media's multi-page website as an intern using WordPress with the Divi theme. Increased traffic using SEO techniques and Google Analytics",
    skills: "Built with: WordPress, HTML, CSS",
    image: "./gif-files/pcimedia.gif",
    link: "https://www.pcimedia.org/",
    github: ""
  },
  {
    title: "Keeper App",
    subtitle: "React Clone of Google Keep",
    description:
      "Keep track of your notes and your to-do's using the Keeper App. Inspired by the Google Keep application.",
    skills: "Built with: React, Material UI",
    image: "./gif-files/keeper-app.gif",
    link: "https://keeper-app-fc.netlify.app/",
    github: "https://github.com/fotinh0/keeper-app"
  }, ...

项目.js

import { projects } from "../data";

export default function Projects() {
  return (
    <section id="projects" className="...">
      <div className="container ...">
        
        {/* additional code here */}

        {/* Projects Cards */}
        <div className="flex flex-wrap -m-4">
          {projects.map((project) => (
            <a
              href={project.link}
              key={project.image}
              className="sm:w-1/2 w-100 p-4">
              
              {/* additional code here */}

              <div className="project-buttons ...">
                <a className="live-site ..." href={project.link} target="_blank"> Live Site</a>
                <a className="github ..." href={project.github} target="_blank">GitHub</a>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

标签: javascriptreactjsbutton

解决方案


使用条件,如下所示:

{project.github && (
  <a className="github ..." href={project.github} target="_blank">GitHub</a>
)}

您可能想检查变量的长度是否大于零,然后您可以执行以下操作:

{project.github.length > 0 && (
  <a className="github ..." href={project.github} target="_blank">GitHub</a>
)}

推荐阅读