簡體   English   中英

如何使用字段作為來自一個 graphql 查詢的過濾器,以獲取單獨查詢中的流體圖像?

[英]How can I use a field as a filter from one graphql query to get a fluid image thats in a separate query?

我有兩個 graphql 源,一個用於流體圖像,一個用於 mongo 數據庫中的字符。 我將字符映射到頁面,我需要使用字符名稱(“allMongodbMobileLegendsdevChamps”中的名稱字段)作為過濾器(可能使用 originalName 過濾器)來查找流體 img。 所以我有這樣的東西

 query MyQuery { allMongodbMobileLegendsdevChamps { nodes { name } } allImageSharp(filter: {fluid: {originalName: {eq: "characterName.jpg"}}}) { nodes { fluid {...allImageSharpFluid } } } }

 const Index = ({ data }) => { const { allMongodbMobileLegendsdevChamps: { nodes: champs }, allImageSharp: { nodes: fluid }, } = data return ( <section className={grid}> {champs.map(champ => { return ( <Link to={`/champ/${champ.name}`}> <Image fluid={fluid.fluid} /> <h3>{champ.name}</h3> </Link> ) })} </section> ) }

如果我沒有使用 graphql,我只需將圖像中的 src 設置為“champ.name”,如下所示:

 <Image src = `/path/to/img/${champ.name}.jpg` />

如何使用 champ.name 過濾我的圖像查詢? 我應該使用 Apollo 來做這樣的事情嗎?

這是 Gatsby,目前不可能,因為您無法將變量傳遞給查詢遵循這個 GH 問題https://github.com/gatsbyjs/gatsby/issues/10482

假設可以傳遞變量,我會將所有字符作為頁面查詢,這將允許我從 props 重構名稱,然后是 static 查詢,我會將名稱作為過濾器傳遞給該查詢。

我使用了這個解決方案並根據我的需要稍微調整了它: graphQL 查詢中的變量

在父組件中我 map 所有冠軍並為每個冠軍創建一個子組件,並將冠軍名稱傳遞給它。

在子組件中,我有一個變量 name,它存儲我想要顯示的圖像的正確節點,方法是使用 find 方法將冠軍名稱與圖像 relativePath 匹配(圖像與冠軍具有相同的確切名稱) . 然后我調用 function renderImage 使用變量“name”並在 node.childImageSharp.fluid 中找到流體圖像,並使用正確的流體圖像位置創建我的圖像組件。

 import React from "react" import { useStaticQuery, graphql } from "gatsby" import { displayName } from "../../utils/championName" import * as S from "../styled/ChampionGridCard" const renderImage = file => { return <S.ChampionImage fluid={file.node.childImageSharp.fluid} /> } const ChampionGridCard = props => { const data = useStaticQuery(graphql` { allFile(filter: { sourceInstanceName: { eq: "champImages" } }) { edges { node { extension relativePath childImageSharp { fluid {...GatsbyImageSharpFluid } } } } } } `) const name = data.allFile.edges.find( image => image.node.relativePath === `ssbu/${props.champName}.jpg` ) return ( <S.ChampionGridCard to={`/champ/${props.champName}`}> <S.ChampionImageWrapper>{renderImage(name)}</S.ChampionImageWrapper> </S.ChampionGridCard> ) } export default ChampionGridCard

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM