【发布时间】:2021-03-01 06:02:10
【问题描述】:
在 Gatsby 中,我使用了页面查询来检索一些数据:
allContentfulArtwork(sort: { fields: [artistName], order: ASC }) {
edges {
node {
image {
fluid(resizingBehavior: SCALE) {
...GatsbyContentfulFluid
}
}
altTag
title
artistName
countryOfOrigin
contentful_id
}
}
}
我将此查询的结果保存在一个名为artworkData 的变量中。我有一个 React 组件,它在 props 中接受此数据以将其呈现到页面(与此问题无关的 props 用 * 标记,可以忽略):
{artworkData.edges.map((artwork) => {
return (
<Artwork
*alreadyVoted={alreadyVoted}
altTag={artwork.node.altTag}
artistName={artwork.node.artistName}
contentful_id={artwork.node.contentful_id}
countryOfOrigin={artwork.node.countryOfOrigin}
*hasVoted={hasVoted}
image={artwork.node.image}
key={artwork.node.contentful_id}
*location={location}
title={artwork.node.title}
></Artwork>
);
})}
我在下面的 TypeScript 界面中定义了Artwork 组件的 props 的形状:
interface ArtworkProps {
alreadyVoted(): void;
altTag: string;
artistName: string;
contentful_id: string;
countryOfOrigin: string;
hasVoted: boolean;
image: GatsbyImage;
location: GatsbyRouteComponentProps;
title: string;
}
我解构了我的道具并在组件中使用它们(为简洁起见,省略了样式化的组件定义):
const Artwork: React.FC<ArtworkProps> = ({ alreadyVoted, altTag, artistName, contentful_id, countryOfOrigin, hasVoted, image, location, title }) => {
return (
<ArtworkWrapper>
<Img fluid={image.fluid} alt={altTag ? altTag : title}></Img>
< /ArtworkWrapper>
// a bunch of additional render code
)
}
不幸的是,TypeScript 说"Property 'fluid' does not exist on type 'GatsbyImage'.ts(2339)"
嗯,我认为确实如此,因为 Gatsby 中的 Img 组件具有 fluid 属性,您可以使用该属性传递流体数据以进行渲染。据我通过the index.d.ts file in Gatsby Image 看到的,这个属性确实存在。如果我们按照层次结构,GatsbyImage 类包含GatsbyImageProps 类型,可以是GatsbyImageFluidProps 接口或GatsbyImageFixedProps 接口; GatsbyImageFluidProps 定义了流体属性。
我正在使用 gatsby 2.26.1、gatsby-image 2.5.0、TypeScript 4.0.5。 VSCode 1.51.1 中显示警告。
【问题讨论】:
-
查询的其余部分是否正确获取数据?
-
@FerranBuireu 确实,所有数据都正确输入。我可以看到图像本身,只是打字问题。
标签: javascript reactjs typescript gatsby gatsby-image