这是我在Stack上的第一个正式帖子,所以请耐心等待;我目前正在使用Nextjs with Sanity作为我的无头CMS,我遇到了什么似乎是一个TypeScript类型的问题. GH:https://github.com/GabrielPedroza/e-commerce/blob/main/components/Product.tsx
<Image src={urlFor(image && image[0]!)} />
import imageUrlBuilder from "@sanity/image-url"
import { SanityImageSource } from "@sanity/image-url/lib/types/types"
export const client = sanityClient({
projectId: "gz95qrem",
dataset: "production",
apiVersion: "2022-04-27",
useCdn: true,
token: process.env.NEXT_PUBLIC_SANITY_TOKEN, // for security purposes
})
const builder = imageUrlBuilder(client)
export const urlFor = (source: SanityImageSource) => {
return builder.image(source)
}
Type 'ImageUrlBuilder' is not assignable to type 'string | StaticImport'.
Property 'src' is missing in type 'ImageUrlBuilder' but required in type 'StaticImageData'.ts(2322)
image.d.ts(19, 5): 'src' is declared here.
image.d.ts(29, 5): The expected type comes from property 'src' which is declared here on type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, "ref" | ... 4 more ... | "loading"> & { ...; }'
Server Error
Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {}
Call Stack
Image
node_modules/next/dist/client/image.js (160:18)
renderWithHooks
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5448:16)
renderIndeterminateComponent
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5521:15)
renderElement
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5736:7)
renderNodeDestructive
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5875:11)
renderNode
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6009:12)
renderHostElement
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5433:3)
renderElement
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5742:5)
renderNodeDestructive
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5875:11)
renderNode
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6009:12)
一种消 debugging 误的方法是只使用字符串或使用ts-ignore,但这显然不能用在我的场景中,因为我使用的是Sanity。我临时的肮脏的解决方案是使用常规的img标签和使用ts-ignore,这样它就可以工作。我试图在官方的Next discord服务器上询问,整体谷歌和阅读文档,但不能真正找到一个解决方案。
2条答案
按热度按时间brgchamk1#
想出了一个干净的解决办法:
tzdcorbm2#
我也有同样的问题。
我的解决方案是:
然后...
希望对任何人都有效