如何在 React 中创建平滑的背景图像过渡?

Don*_*eal 4 css reactjs

我有一个标头,其类名根据状态而变化。每个类都有不同的背景图像,在 CSS 中指定。一切工作正常,但过渡非常突然,没有淡入效果。

我写:

.jumbotron-img-1{
    background-image: url("/images/myImg1.jpg");
    transition: all 1s ease-in-out;
Run Code Online (Sandbox Code Playgroud)

它有效,但很丑。在图像以最终形式显示之前,会进行缩放和扭曲。我在 Google 上看过一些教程,但没有什么是简单的,也没有达到纯 CSS 或 React 中的背景图像转换的目的。

任何帮助将不胜感激,谢谢!

Gau*_*wat 5

background-image 不是可动画的属性。我觉得最符合您的目的的是渲染多个标头,其中所有可用的类名相对于position: absolute;公共父级相互堆叠,并根据您的状态中处于活动状态的类名使用属性仅使其中一个可见opacity,并使用转换opacity

示例工作代码:

render() {
   const {imgClassList} = this.props;
   const {activeimgClass} = this.state;
   return (
     <div className="header-container">
       {imgClassList.map(imgClass => {
         return (
           <div 
             className={`header ${imgClass} ${(imgClass === activeimgClass)? 'active' : ''}`}
           />)
       })}
     </div>
   )
}
Run Code Online (Sandbox Code Playgroud)

css 应该是这样的:

.header-container {
  position: relative;
}
.header{
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0
  transition: opacity 1s ease-in-out;
}
.header.active {
  opacity: 1
}
.img-1 {
  background:url('images/img-1')
}
.img-2 {
  background: url('images/img-2')
} ... and so on
Run Code Online (Sandbox Code Playgroud)