本文介绍了动态背景图片反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据 item.imageLinks.smallThumbnail 的值动态选择 backgroundImage .

I am trying to select backgroundImage dynamically based on value of item.imageLinks.smallThumbnail.

如果我的API返回的数组具有 smallThumbnail URL,那么我想将其用作 backgroundImage 或使用本地默认的 backgroundImage ../public 中的 book.png 的内容.

If the array returned by my API has a smallThumbnail URL then I want to use that as the backgroundImage or use a local default backgroundImage of book.png inside ../public.

下面是我的代码,但是当 item.imageLinks.smallThumbnail undefined 且不使用替代的 book.png 时,它不起作用但给我错误:

Below is my code, but it's not working when item.imageLinks.smallThumbnail is undefined and it's not using the alternate book.png but giving me the error:

类型错误:无法读取未定义的"smallThumbnail"

请帮助.

谢谢

return(
        <ol className="books-grid">
          {book.map( (item)  => (
              <li key={item.id}>
                <div className="book">
                  {item.shelf && (
                      <div className="book-top">
                        <div 
                          className="book-cover" 
                          style={{ width: 128, height: 193, backgroundImage: `url({${item.imageLinks.smallThumbnail} || ../public/book.png } )` }}></div>

推荐答案

如果 imageLinks 未定义,则该对象不是对象,因此您将无法使用点语法,因此尝试获取 smallThumbnail 属性的错误.

If imageLinks is undefined then it is not an object so you won’t be able to use dot syntax, hence the error trying to get the smallThumbnail property.

尝试以下方法:

<div
  className="book-cover"
  style={{
    width: 128,
    height: 193,
    backgroundImage: `url(${(item.imageLinks && item.imageLinks.smallThumbnail) || "../public/book.png"})`
  }}
></div>

...,因此您首先要检查图像链接.

... so you are checking for imageLinks first.

这篇关于动态背景图片反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 16:05