我正在使用 React 和 Redux,我遇到了以下情况。在我的组件中,我有一个包含图像的 div,并且该组件还从我的 Redux 状态接收一个名为 showIcon
的属性。所以,如果 showIcon
不为 null,我希望图像显示 5 秒,5 秒过后,我希望它消失并设置 showIcon
值null
通过调度一个我有的 Action ,比如 updateShowIcon(null);
。我怎样才能在 React 中正确地做到这一点,我怎样才能使用 CSS 根据需要显示和动画化图标?
import React, { Component } from 'react';
class MyComp extends Component {
render() {
return (
<div style={styles.mainDiv}>
<div style={styles.childDiv}>
{
this.props.showIcon &&
<div style={styles.iconStlyes}>
<img src={process.env.PUBLIC_URL + '/icons/myicon.png'}/>
</div>
}
// partially removed for brevity, some other component
</div>
</div>
);
}
}
const styles = {
iconStlyes: {
position: 'absolute',
zIndex: 10,
},
mainDiv: {
overflow: 'auto',
margin: 'auto',
height: 'calc(100vh - 64px)',
padding: 0,
},
childDiv: {
height: 'calc(100vh - 64px)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
};
export default MyComp;
最佳答案
每当我检测到 componentWillReceiveProps
发生变化时,我都会创建一个计时器并调度操作。请记住清除 componentWillUnmount
上的超时。
这个想法是基于你用 css 显示和隐藏图标而不是 react 条件渲染,所以一旦你需要显示你添加类 show
的图标或者在你不需要时删除它显示它。
它可能看起来像这样:
componentWillReceiveProps(nextProps){
if (nextProps.showIcon && nextProps.showIcon !== this.props.showIcon){
this.timer = setTimeout(() => {nextProps.updateShowIcon(null)}, 5000);
}
}
componentWillUnmount(){
clearTimeout(this.timer);
}
render() {
const {showIcon} = this.props;
return (
<div style={styles.mainDiv}>
<div style={styles.childDiv}>
<div style={styles.iconStlyes} className={`${showIcon ? 'show':''} icon-container`}>
<img src={process.env.PUBLIC_URL + '/icons/myicon.png'}/>
</div>
</div>
</div>
);
}
以及用于简单淡入淡出动画的 CSS:
.icon-container{
opacity: 0;
transition: opacity: 500ms ease-in;
}
.icon-container.show{
opacity: 1;
}
关于javascript - 如何使用 CSS 在 React 中为图像设置动画 5 秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49718239/