我正在 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/