【发布时间】:2021-03-29 12:51:36
【问题描述】:
我正在构建一个天气/旅行信息单页网站,作为 React 中的投资组合/实践项目。页面顶部有一个很大的“jumbotron”风格元素,中间是搜索栏。默认情况下,它会显示一张海滩的通用照片,然后一旦搜索到一个城市,它就会变为该城市的一张照片,从自定义的 Google 图片搜索 API 中提取。
这一切都很好,但我希望一张图片能够淡入另一张而不是突然改变!我查看了 react-bootstrap 和 react-transitions-group 文档,但没有找到任何明显可以做到这一点的东西。
目前在顶级 App 组件中,我正在使用状态“imgUrl”,该状态会更新为新图像的 URL,以便在 API 返回时显示。那么 JSX 元素的 backgroundImage 属性就是 this.state.imgUrl。
应用组件:
import React from 'react';
import Searchbar from './components/Searchbar'
import Weather from './components/Weather'
import background from './default-bg.jpg'
import Attractions from './components/Attractions'
import ImageSearch from './components/ImageSearch'
import './App.css'
class App extends React.Component {
state = {
city: '',
searched: false,
lat: '',
lon: '',
imgPath: background,
mainHeight: '596px'
}
city = (text) => {
this.setState({ city: text, mainHeight: '400px' })
}
searched = (isSearched) => {
this.setState({ searched: isSearched })
}
imgPath = (imgUrl) => {
this.setState({ imgPath: imgUrl })
}
render() {
return (
<div className="App">
<div className="jumbotron justify-content-center align-items-center" style={{textAlign: "center", height: this.state.mainHeight, backgroundImage: `url(${this.state.imgPath})`, backgroundSize: "100%", backgroundPosition: "bottom", margin: "0"}}>
<div className="container" style={{ width: "35%", backgroundColor: "seashell", opacity: "0.75", padding: "0 40px 10px 40px", borderRadius: "20px" }}>
<span style={{ fontSize: "6em", fontWeight: "bold" }}>Snapshot</span>
<h4 style={{ fontWeight: "bold" }}>The world at a glance</h4>
</div>
<br></br>
<Searchbar city={this.city} searched={this.searched} />
</div>
{this.state.searched === true &&
<div>
<Weather city={this.state.city} />
<Attractions city={this.state.city} />
<ImageSearch city={this.state.city} imgPath={this.imgPath} />
</div>
}
</div>
);
}}
export default App
图片搜索组件:
import React, { Component } from 'react'
export default class ImageSearch extends Component {
state = {
city: this.props.city,
cx: ###
apiKey: ###
imgUrl: ''
}
async componentDidMount() {
const imgSearchUrl = `https://www.googleapis.com/customsearch/v1?q=${this.state.city}&num=1&searchType=image&key=${this.state.apiKey}&cx=${this.state.cx}`
try {
const imgRes = await fetch(imgSearchUrl)
if (imgRes.ok) {
const imgJson = await imgRes.json()
console.log(imgJson)
this.setState({ imgUrl: imgJson.items[0].link })
this.props.imgPath(this.state.imgUrl)
}
} catch (error) {
console.log(error)
}
}
render() {
return (
<React.Fragment />
)
}
}
【问题讨论】:
-
请分享您目前拥有的代码示例,更多信息请参阅stackoverflow.com/help/how-to-ask
-
更改
src总是很突然,React 或 vanilla。要在图像之间淡入淡出,您通常需要使用两个图像,不透明度和 CSS/JS 动画。 -
@James Bradenburg - 请参阅下面的评论,该评论提供了几个应用于图像的特定 CSS 属性。干杯!