在React中的CSS中使用this.state

问题描述 投票:0回答:1

我正在使用React,Axios和MovieDB API制作电影搜索应用程序。我遇到一个问题,想使const background = res.data['results'][0]['backdrop_path'] this.setState({ background })在CSS中显示为背景图像。我不确定这是否可行,或者是否有更好的方法来做到这一点。

代码:

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 = '************************';
    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() {
    return (
      <html style="background-image:URL(https://image.tmdb.org/t/p/w500${this.state.background})">
        <div>
      <input type="search" id="search" onKeyDown={event => this.clickHandler(event)} />
      <h1>{this.state.title}</h1>
      <h1>{this.state.popularity}</h1>
      <img src={`https://image.tmdb.org/t/p/w300${this.state.poster}`} />
      </div>
    </html>

    )
  }
}
reactjs api this
1个回答
1
投票

您可以使用style属性设置背景图像,该属性必须是一个对象。例如


const backgroundStyle = {
  backgroundImage: `url(https://image.tmdb.org/t/p/w500${this.state.background})`,
  backgroundSize: "cover"
  // you can use any other style properties here
  // just keep in mind that key have to be camelCased, no dashes in between
  // and values have to strings
}

return (
  // ...
  <div style={backgroundStyle}>

  </div>
)
© www.soinside.com 2019 - 2024. All rights reserved.