动态更改背景图像

Change the background image dynamically

我想在评论的帮助下修改后台图像。

图片来自tmdb API。 所以我认为你必须创建一个背景图像组件并将其传递给 URL.

我知道 CSS 有背景图像 属性,但它适用于静态图像 ...

最好的方法是什么,我想让这个组件可重用。

这是您必须执行的操作。

  1. 使用默认 background-image
  2. 创建您的 <div> 及其 style
  3. 创建 3 <button> 来触发你的函数 changeImage() 并提供一个参数
  4. style.backgroundImage 更改为 JavaScript,如下所示:

function changeImage(category){
  document.getElementById('div-bg').style.backgroundImage = 'url("https://source.unsplash.com/320x240/?' + category + '")';
}
#div-bg {
  display: block;
  width: 320px;
  height: 240px;
  background-image: url("https://source.unsplash.com/320x240/?sky");
}
<div id="div-bg"></div>

<button onclick="changeImage('nature')">Nature</button>
<button onclick="changeImage('animal')">Animal</button>
<button onclick="changeImage('fire')">Fire</button>

如有任何问题,欢迎提问!

通过这样做,它起作用了,我有我的背景。但是我没有设法用可重用的组件来做到这一点

import React from 'react';

  const VideoDetail = ({ title, description, background }) => {

  const IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500/";

  const backgroundStyle = {
    color: 'white',
    backgroundRepeat: 'no-repeat',
    backgroundAttachment: 'scroll',
    backgroundPosition: 'center',
    backgroundSize: 'cover',
    width: "100%",
    height: "400px",
    backgroundImage: `url(${IMAGE_BASE_URL}${background})`
 };

 return(
    <div>
      <div style={background !== undefined ? backgroundStyle : null }>
        <h1>{title}</h1>
        <p>{description}</p>
      </div>
  </div>
  )
} 
export default VideoDetail;import React from 'react';