【发布时间】:2019-12-13 21:49:34
【问题描述】:
我正在尝试在 ReactJS 中的两个背景图像之间进行一些转换。在这里,我在首先显示 backgroundImage 的阶段被阻止,使用 ReactJS 元素的内联样式属性。
这里有一个演示:https://stackblitz.com/edit/react-evdqgw?file=index.js
这是我的 ReactJS 的 sn-p:
import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
class App extends Component {
constructor(props){
super(props);
this.imageSliderRef=React.createRef()
}
state = {
currentImageIndex: 0,
imageUrlStock:[
"https://picsum.photos/640/480?image=1",
"https://picsum.photos/640/480?image=2",
"https://picsum.photos/640/480?image=3"
],
currentBackgroundImage:{},
formerBackgroundImage:{}
};
componentDidMount() {
this.interval = setInterval(() => {
this.nextSlide(); //this function change the index state.
}, 3000);
console.log("this.state: ", this.state)
}
nextSlide() {
const lastIndex = this.state.imageUrlStock.length - 1;
const { currentImageIndex } = this.state;
const index = (currentImageIndex + 1) % (lastIndex + 1)
// @See https://css-tricks.com/restart-css-animation/
const elm = this.imageSliderRef
/* .querySelector('[class^="pic"],[class*=" pix"]');
elm.className = `pic${index+1}`
*/
// const newone = elm.cloneNode(true);
// elm.parentNode.replaceChild(newone, elm);
this.setState(currentState => ({
currentImageIndex: index,
currentBackgroundImage:currentState.imageUrlStock[index],
formerBackgroundImage:currentState.imageUrlStock[index-1]
}));
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
console.log(`
this.state.currentBackgroundImage,
this.state.formerBackgroundImage`,
this.state.currentBackgroundImage,
this.state.formerBackgroundImage
)
return (
<div ref={this.imageSliderRef} className="imageSlider"
>
<img className="current" style={{backgroundImage:`url(${this.state.currentBackgroundImage})`}}/>
<div className="former" style={{backgroundImage:`url(${this.state.formerBackgroundImage})`}}/>
</div>
);
}
}
render(<App />, document.getElementById('root'));
这是我的 css 的 sn-p:
h1, p {
font-family: Lato;
}
body {
position: relative;
width: 640px;
height: 480px;
}
.imageSlider> {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 640px;
height: 480px;
}
.current {
z-index: 2;
opacity: 0;
animation: in 3s 0s;
/* background-image:url("https://picsum.photos/640/480?image=1");*/
}
.former {
z-index: 1;
opacity: 1;
}
#root .pic1.init .former {
background-image: none;
}
/*
#root .pic1 .current,
#root .pic2 .former {
background-image: url("https://picsum.photos/640/480?image=1");
}
#root .pic2 .current,
#root .pic3 .former {
background-image: url("https://picsum.photos/640/480?image=2");
}
#root .pic3 .current,
#root .pic1 .former {
background-image: url("https://picsum.photos/640/480?image=3");
}
*/
@keyframes in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
【问题讨论】:
-
这是一个
<img/>标签,所以你应该使用src属性,而不是给它一个CSS背景图片。<img className="current" src={this.state.currentBackgroundImage} />就是你想要的 -
抱歉, 元素是我在发布帖子之前的拼写错误,最初它实际上是一个 div 元素,请参阅我的回答以更好地理解我的问题 –
标签: javascript css reactjs