简体   繁体   English

动态更改背景图片

[英]Change the background image dynamically

I would like to modify the image in the background with the help of a comment. 我想借助评论在后台修改图像。

The images come from the tmdb API. 图像来自tmdb API。 So I think you have to create a background image component and pass it on to the URL. 因此,我认为您必须创建一个背景图像组件并将其传递给URL。

I know that CSS has the background-image property, but it works for static images ... 我知道CSS具有background-image属性,但是它适用于静态图像...

What is the best method, I would like to make this component reusable. 什么是最好的方法,我想使此组件可重用。

Here is how you would have to do it. 这是您将必须执行的操作。

  1. Create your <div> and its style with a default background-image 使用默认background-image创建<div>及其style
  2. Create 3 <button> to triggers your function changeImage() and provide a parameter 创建3个<button>来触发函数changeImage()并提供一个参数
  3. Change the style.backgroundImage with JavaScript such as below: 使用JavaScript更改style.backgroundImage ,如下所示:

 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> 

If you have any question, please ask! 如有任何疑问,请询问!

By doing this it works, I have my background. 通过这样做,我有了自己的背景。 But I did not manage to do it with a reusable component 但是我没有设法使用可重用的组件

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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM