React项目中Sanity ImageUrlBuilder出现不支持类型错误求助
React + Sanity 图片URL报错:The provided 'src' attribute is an unsupported type ImageUrlBuilder
问题场景
制作作品集React项目时,仅在调用Testimonial组件时触发该错误,其他组件中ImageUrlBuilder可正常工作,错误提示为:The provided 'src' attribute is an unsupported type ImageUrlBuilder
组件代码
const Testimonial = () => { const [currentIndex, setCurrentIndex] = useState(0); const [testimonials, setTestimonials] = useState([]); const [brands, setBrands] = useState([]); const handleClick = (index) => { setCurrentIndex(index); }; useEffect(() => { const query = '*[_type == "testimonials"]'; const brandsQuery = '*[_type == "brands"]'; client.fetch(query).then((data) => { setTestimonials(data); }); client.fetch(brandsQuery).then((data) => { setBrands(data); }); }, []); return ( <> {testimonials.length && ( <> <div className="app__testimonial-item app__flex"> <img src={urlFor(testimonials[currentIndex].imgurl)} alt={testimonials[currentIndex].name} /> <div className="app__testimonial-content"> <p className="p-text">{testimonials[currentIndex].feedback}</p> <div> <h4 className="bold-text">{testimonials[currentIndex].name}</h4> <h5 className="p-text">{testimonials[currentIndex].company}</h5> </div> </div> </div> <div className="app__testimonial-btns app__flex"> <div className="app__flex" onClick={() => handleClick(currentIndex === 0 ? testimonials.length - 1 : currentIndex - 1)}> <HiChevronLeft /> </div> <div className="app__flex" onClick={() => handleClick(currentIndex === testimonials.length - 1 ? 0 : currentIndex + 1)}> <HiChevronRight /> </div> </div> </> )} <div className="app__testimonial-brands app__flex"> {brands.map((brand) => ( <motion.div whileInView={{ opacity: [0, 1] }} transition={{ duration: 0.5, type: 'tween' }} key={brand._id} > <img src={urlFor(brand.imgUrl)} alt={brand.name} /> </motion.div> ))} </div> </> ); }; export default AppWrap( MotionWrap(Testimonial, 'app__testimonial'), 'testimonial', 'app__primarybg', );
错误原因
urlFor() 返回的是ImageUrlBuilder对象,而img标签的src属性要求传入字符串格式的URL,你漏掉了把Builder转换为字符串的关键步骤。其他组件能正常工作,应该是已经在urlFor()后面调用了.url()方法。
修复方法
在所有使用urlFor()的位置,末尾加上.url()方法,将Builder对象转为可直接使用的URL字符串:
- 修复 testimonial 头像的img标签:
<img src={urlFor(testimonials[currentIndex].imgurl).url()} alt={testimonials[currentIndex].name} />
- 修复 brands 列表的img标签:
<img src={urlFor(brand.imgUrl).url()} alt={brand.name} />
额外优化建议
为了避免图片字段为空时出现报错,建议增加空值判断:
// Testimonial头像部分 {testimonials[currentIndex].imgurl && ( <img src={urlFor(testimonials[currentIndex].imgurl).url()} alt={testimonials[currentIndex].name} /> )} // Brands图片部分 {brand.imgUrl && ( <img src={urlFor(brand.imgUrl).url()} alt={brand.name} /> )}
内容的提问来源于stack exchange,提问作者Ammad Ali
相关产品推荐
相关产品推荐

