javascript - 使用 gatsby-source-google-spreadsheet 将表格中的链接插入 Gatsby

标签 javascript reactjs graphql gatsby

我正在 Gatsby 中使用 gatsby-source-google-spreadsheet 插件在页面上创建元素列表。该插件已与我的表格一起设置并且运行良好。我正在努力解决如何插入链接作为 <a href>当我将其从工作表中拉出时。

src/pages/index.js :

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



export default ({ data }) => {
  const sheetData = data.allGoogleSpreadsheetSheetSheet.nodes;
  const rendered = sheetData.map(item =>
    <div className="section">

      <div className="section__when"> {item.day}, {item.date} at {item.time} </div>
      <div className="section__host"> {item.event}, {item.host} </div>
      <div className="section__link"> <a href="{item.link}" target="_blank">Access here. </a></div>
      <div className="section__description"> {item.description} </div>
    </div>);

  return rendered;
};


export const query = graphql`
  query {
    allGoogleSpreadsheetSheetSheet {
      nodes {
        event
        host
        link
        day
        time
        date
        description
      }
    }
  }
`;

这给了我一个合适的列表,但是当我单击链接时,它试图将我带到:http://localhost:8000/%7Bitem.link%7D ,这显然是错误的。现在,我的表格只有链接 https://www.google.com对于每个条目。如何更改链接 div 的结构方式以使其转到外部链接?

最佳答案

如果您检查链接,您会发现 %7Bitem.link%7D 中有您的变量名称。字面意思是{item.link} ,因此您的代码无法识别该变量,并且它作为字符串 {item.link} 插入.

假设您正在正确检索和接收变量数据,正如您所说。

试试这个:

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



export default ({ data }) => {
  const sheetData = data.allGoogleSpreadsheetSheetSheet.nodes;
  const rendered = sheetData.map(item =>
    <div className="section">

      <div className="section__when"> {item.day}, {item.date} at {item.time} </div>
      <div className="section__host"> {item.event}, {item.host} </div>
      <div className="section__link"> <a href=`${item.link}` target="_blank">Access here. </a></div>
      <div className="section__description"> {item.description} </div>
    </div>);

  return rendered;
};


export const query = graphql`
  query {
    allGoogleSpreadsheetSheetSheet {
      nodes {
        event
        host
        link
        day
        time
        date
        description
      }
    }
  }
`;

找出 anchor 标记中的差异:<a href=`${item.link}` target="_blank">

基本上你正在使用 template literals从 ES6 开始。它们是允许嵌入表达式的字符串文字,并用反引号 (`)(重音符号)字符而不是双引号或单引号括起来。

关于javascript - 使用 gatsby-source-google-spreadsheet 将表格中的链接插入 Gatsby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60821153/

相关文章:

javascript - range.insertNode() 没有按预期插入文本节点

javascript - 许多来自 JSON 的 href,在切换单击时会出现不同的 id

javascript - 如何在 react 中传递具有已知字段的对象作为 Prop

reactjs - 无法在 React Native 应用程序中使用 React.memo

javascript - 如何在 GraphQL (Relay) 中查询和改变数组类型?

javascript - 在 React 中使用相同处理函数切换多个 div 的优化方式

javascript - 命名空间外部 Javascript 无法从目标 javascript 访问

reactjs - google 域上 netlify 的 DNS 设置是什么?

node.js - 如何在 node.js 的 GraphQL 中使 InputType 灵活?

meteor - Apollo/GraphQl-类型必须为输入类型