【问题标题】:How to add a linear gradient to a background image in ReactJs如何在 ReactJs 中为背景图像添加线性渐变
【发布时间】:2020-06-10 10:19:43
【问题描述】:

我正在使用 Reactjs、Axios 和 MovieDB API 制作电影搜索应用程序。我目前正在使用以下代码获取 API 的背景图片:

const backgroundStyle = {
       backgroundImage: `url(https://image.tmdb.org/t/p/w500${this.state.background})`,
       backgroundSize: "cover",
       height: "100vh"
     }

我想为背景图片添加一个线性渐变,但是当我尝试这样做时:

background: linear-gradient

background: linearGradient

react 还是黄色的,不知道怎么实现。我要使用的代码是:

linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), `url(https://image.tmdb.org/t/p/w500${this.state.background})`;

但是放入 Reactjs 格式。

完整代码在这里:

import React from 'react';
import axios from 'axios';
import '../CSS/style.css'

export default class Movielist extends React.Component {
  state = {
    title: "",
    popularity: "",
    poster: "",
    background: "",
  }

    clickHandler = (event) => {
        if (event.keyCode === 13) {
           const query = event.target.value;
           const API_KEY = 'caf02a958f137f43327649b2b8721302';
    axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`)
      .then(res => {
        const title = res.data['results'][0]['title'];
        this.setState({ title });

        const popularity = res.data['results'][0]['popularity']
        this.setState({ popularity });

        const poster = res.data['results'][0]['poster_path']
        this.setState({ poster });

        const background = res.data['results'][0]['backdrop_path']
        this.setState({ background })


      })
        }
    }

  render() {
    const backgroundStyle = {
       backgroundImage: `url(https://image.tmdb.org/t/p/w500${this.state.background})`,
       backgroundSize: "cover",
       height: "100vh"
     }

    return (
      <div id="main-div" style={backgroundStyle}>
        <div id="second-div">
         <input type="search" id="search" onKeyDown={event => this.clickHandler(event)} />
         <h1 id="title">Title: {this.state.title}</h1>
         <h1 id="popularity">Popularity: {this.state.popularity}</h1>
         <img id="poster" src={`https://image.tmdb.org/t/p/w300${this.state.poster}`} />
      </div>
    </div>

    )
  }
}

【问题讨论】:

    标签: reactjs api


    【解决方案1】:

    您可以在创建backgroundStyle 时在属性backgroundImage 中应用渐变。例如,

    const backgroundStyle = {
        backgroundImage: `linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), 
    url(https://image.tmdb.org/t/p/w500${this.state.background})`,
    
        backgroundSize: "cover",
        height: "100vh"
    }
    

    backgroundImage 的值需要是一个字符串,你可以像往常一样为它写 css 属性值,只要它在一个字符串内。请记住,这些值将被内联,因此将是最具体的。

    【讨论】:

    • 我很高兴它有帮助。不要忘记接受作为答案:)。
    猜你喜欢
    • 2023-03-31
    • 2023-03-08
    • 1970-01-01
    • 2022-11-02
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    相关资源
    最近更新 更多