Javascript 如何将API调用的图像结果作为背景图像附加到我的应用程序?
所以我要做的事情的背景。。用户输入城市,背景将更改为该城市的图像,该图像是通过对Pixabay API的API调用获取的。我将结果作为变量“background”保存,但我不知道如何将其附加到页面的背景中。“const background”变量本身呈现图像URL。这意味着,当我使用console.log(background)时,我会得到要应用于整个页面的背景图像的URLJavascript 如何将API调用的图像结果作为背景图像附加到我的应用程序?,javascript,css,reactjs,api,Javascript,Css,Reactjs,Api,所以我要做的事情的背景。。用户输入城市,背景将更改为该城市的图像,该图像是通过对Pixabay API的API调用获取的。我将结果作为变量“background”保存,但我不知道如何将其附加到页面的背景中。“const background”变量本身呈现图像URL。这意味着,当我使用console.log(background)时,我会得到要应用于整个页面的背景图像的URL import React, { Component } from "react"; import Title from "
import React, { Component } from "react";
import Title from "./Title.js";
import Form from "./Form.js";
import Weather from "./Weather.js";
import axios from "axios";
// import logo from "./logo.svg";
import "./App.css";
const API_KEY = "b6907d289e10d714a6e88b30761fae22";
// const API_ID = "12653279-f2ae53f8bfb342d39b6cbf92b";
class App extends Component {
// the initial state of the application is set below, will change upon submit of button
state = {
temperature: undefined,
city: undefined,
description: undefined,
error: undefined,
searchText: "",
apiUrl: "https://pixabay.com/api",
apiKey: "12653279-f2ae53f8bfb342d39b6cbf92b",
images: []
};
getweatherData = async e => {
// arrow function used as an alternative to constructor to bind data and use "this" to still be bound to component
// async returns a promsise to be settled
e.preventDefault();
// e argument passed in the async function is now used to prevent refresh default action
const city = e.target.elements.city.value;
// a way that we can make the city value dynamic within the api url in the api call
const api_call = await fetch(
// await key word pauses the function until data is recieved from api call
`https://openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}`
);
const data = await api_call.json();
// above, the data recieved from the API is converted to json readable format
console.log(data);
if (data.cod === 404) {
throw Error(data.message);
} else {
this.setState({
temperature: data.main.temp.toFixed(0),
city: data.sys.city,
country: data.sys.country,
description: data.weather[0].description,
error: "undefined"
});
}
axios
.get(
`${this.state.apiUrl}/?key=${
this.state.apiKey
}&q=${city}&image_type=photo&per_page="1"
}&safesearch=true&editorschoice= true`
)
.then(res => {
this.setState({ images: res.data.hits });
const background = res.data.hits[1];
console.log(background);
});
};
render() {
return (
<div className="container">
<Title />
{/* setting up a prop to the getweatherData value so we can have access to it in the form.js */}
<Form getweatherData={this.getweatherData} />
{/* defining props so they can be accessed in the weather.js */}
<Weather
temperature={this.state.temperature}
city={this.state.city}
country={this.state.country}
description={this.state.description}
error={this.state.error}
/>
</div>
);
}
}
export default App;
import React,{Component}来自“React”;
从“/Title.js”导入标题;
从“/Form.js”导入表单;
从“/Weather.js”导入天气;
从“axios”导入axios;
//从“/logo.svg”导入徽标;
导入“/App.css”;
const API_KEY=“b6907d289e10d714a6e88b30761fae22”;
//const API_ID=“12653279-f2ae53f8bfb342d39b6cbf92b”;
类应用程序扩展组件{
//应用程序的初始状态设置如下,将在按钮提交后更改
状态={
温度:未定义,
城市:未定义,
说明:未定义,
错误:未定义,
搜索文本:“”,
apiUrl:“https://pixabay.com/api",
apiKey:“12653279-f2ae53f8bfb342d39b6cbf92b”,
图片:[]
};
getweatherData=async e=>{
//arrow函数用作构造函数的替代,用于绑定数据,并使用“this”仍然绑定到组件
//async返回要结算的承诺
e、 预防默认值();
//异步函数中传递的参数现在用于防止刷新默认操作
const city=e.target.elements.city.value;
//我们可以在api调用中使城市值在api url内动态的一种方法
const api_call=等待获取(
//wait关键字暂停函数,直到从api调用接收到数据
`https://openweathermap.org/data/2.5/weather?q=${city}&appid=${API\u KEY}`
);
const data=wait api_call.json();
//上面,从API接收的数据被转换为json可读格式
控制台日志(数据);
如果(data.cod==404){
抛出错误(data.message);
}否则{
这是我的国家({
温度:固定的数据主温度(0),
城市:data.sys.city,
国家:data.sys.country,
description:data.weather[0]。description,
错误:“未定义”
});
}
axios
.得到(
`${this.state.apiUrl}/?键=${
这个.state.apiKey
}&q=${city}&image\u type=photo&per\u page=“1”
}&safesearch=true&editorschoice=true`
)
。然后(res=>{
this.setState({images:res.data.hits});
const background=res.data.hits[1];
控制台日志(后台);
});
};
render(){
返回(
{/*设置getweatherData值的道具,以便我们可以以.js*/}的形式访问它
{/*定义道具,以便在weather.js*/}
);
}
}
导出默认应用程序;
形式。js
import React, { Component } from "react";
class Form extends Component {
render() {
return (
// a react attribute onSubmit to call in our prop
<form onSubmit={this.props.getweatherData}>
<input type="text" name="city" placeholder="City..." />
{/* <input type="text" name="country" placeholder="Country..." /> */}
<button>Get Weather</button>
</form>
);
}
}
export default Form;
import React,{Component}来自“React”;
类形式扩展组件{
render(){
返回(
//Submit上的react属性调用我们的道具
{/* */}
天气预报
);
}
}
导出默认表单;
将背景图像设置为状态,然后在希望显示的任何元素上使用内联样式。像这样的
...
const background = res.data.hits[1];
this.setState({ background })
...
return (
<div className="container" style={{ this.state.background ? { background: this.state.background } : {} }}>
...
。。。
const background=res.data.hits[1];
this.setState({background})
...
返回(
...
您正在尝试更改此元素的背景
?背景的结果是url吗?很抱歉,我不明白,背景变量本身是图像url。这意味着当我控制台.log(背景)时我得到了我想应用于整个页面的背景图像的URL,我不明白这些标记指的是什么,我只是把点放在那里,让它更清楚你需要更改哪些部分。在你从API获取图像URL后,你在一个变量中得到了图像URL。将这个变量设置为状态,这样你就可以访问它在渲染函数中,通过状态对象访问它,然后使用样式属性应用它。