当图像在一段时间后发生变化时,如何在 React 中对图像进行动画处理?



我正在尝试在 react 中制作一个图像滑块,其中 5000 秒后image发生变化。 我从这里检查了 http://mumbaimirror.indiatimes.com/该网站实现该功能的位置。 我试图在反应中实现相同的内容。我能够做到这一点,但我的图像不是幻灯片(从右到左(,换句话说,当第二个图像显示 n 视图时,图像不显示动画 这是我的代码 https://codesandbox.io/s/YrO0LvAA

constructor(){
super();
this.pre=this.pre.bind(this);
this.next=this.next.bind(this);
this.state ={
currentSlide :0
}
setInterval(()=>{
var current = this.state.currentSlide;
var next = current + 1;
if (next > this.props.stories.items.length - 1) {
next = 0;
}
this.setState({ currentSlide: next });
}, 5000);

}

一种方法是始终在右侧准备好未来的图像(下一个图像(,以便您可以将其向左过渡,同时将当前图像向左过渡。所以他们俩一起行动。

在 React 中,这意味着您需要存储当前图像和下一个图像的索引,并且每 X 秒您需要将它们向左移动(或向右移动,具体取决于您的操作(

下面是一个概念证明:

https://codepen.io/nashio/pen/xLKepZ

const pics = [
'https://cdn.pixabay.com/photo/2017/06/19/07/12/water-lily-2418339__480.jpg',
'https://cdn.pixabay.com/photo/2017/07/18/18/24/dove-2516641__480.jpg',
'https://cdn.pixabay.com/photo/2017/07/14/17/44/frog-2504507__480.jpg',
'https://cdn.pixabay.com/photo/2016/09/04/13/08/bread-1643951__480.jpg',
];
class App extends React.Component {
constructor(props) {
super(props);
const idxStart = 0;
this.state = {
index: idxStart,
next: this.getNextIndex(idxStart),
move: false,
};
}
getNextIndex(idx) {
if (idx >= pics.length - 1) {
return 0;
}
return idx + 1;
}
setIndexes(idx) {
this.setState({
index: idx,
next: this.getNextIndex(idx)
});
}
componentDidMount() {        
setInterval(() => {
// on
this.setState({
move: true
});
// off
setTimeout(() => {
this.setState({
move: false
});
this.setIndexes(this.getNextIndex(this.state.index));
}, 500); // same delay as in the css transition here
}, 2000); // next slide delay
}
render() {
const move = this.state.move ? 'move' : '';
if (this.state.move) {
}
return (
<div className="mask">
<div className="pic-wrapper">
<div className={`current pic ${move}`}>
{this.state.index}
<img src={pics[this.state.index]} alt="" />
</div>
<div className={`next pic ${move}`}>
{this.state.next}
<img src={pics[this.state.next]} alt="" />
</div>
</div>
</div>
);
}
}
React.render(<App />, document.getElementById('root'));

// CSS
.pic {
display: inline-block;
width: 100px;
height: 100px;
position: absolute;
img {
width: 100px;
height: 100px;
}
}
.current {
left: 100px;
}
.current.move {
left: 0;
transition: all .5s ease;
}
.next {
left: 200px;
}
.next.move {
left: 100px;
transition: all .5s ease;
}
.pic-wrapper {
background: lightgray;
left: -100px;
position: absolute;
}
.mask {
left: 50px;
overflow: hidden;
width: 100px;
height: 120px;
position: absolute;
}

编辑:更新了POC以处理左右导航,在此处查看完整内容

这绝不是一个优雅的解决方案,但它确实在图像首次出现时从左侧滑入:https://codesandbox.io/s/xWyEN9Yz

我认为你遇到的问题是因为你只渲染了当前的故事,但你的大部分代码似乎假设会有一个滚动的故事轮播,你可以像卷轴一样动画化。

使用滚动轮播方法,只需对左侧CSS属性进行动画处理,并根据当前可见的故事进行调整即可。 即在组件中维护某种状态,即当前索引,然后将故事容器的"left"样式属性设置为该索引的倍数。例如:

const getLeftForIndex = index => ((index*325) + 'px');
<div className="ImageSlider" style={{ left: getLeftForIndex(currentStory) }}>
<Stories />
</div>

最新更新