javascript - 如何使用 CSS 在 React 中为图像设置动画 5 秒?

标签 javascript css reactjs

我正在使用 React 和 Redux,我遇到了以下情况。在我的组件中,我有一个包含图像的 div,并且该组件还从我的 Redux 状态接收一个名为 showIcon 的属性。所以,如果 showIcon 不为 null,我希望图像显示 5 秒,5 秒过后,我希望它消失并设置 showIconnull 通过调度一个我有的 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/

相关文章:

Javascript DOMContentLoaded 事件未在 Internet Explorer 中触发

javascript - 如何在 iframe 包含的外部页面上显示隐藏的 div

javascript - 如何为react-datepicker将UTC日期转换为 "MM/DD/YYYY"?

reactjs - Gatsby 构建失败,因为 React hook 中未定义窗口

javascript - 如何通过javascript设置ngModelOptions?

javascript - 将我在 Google Analytics 中的目标 url 与正则表达式匹配

javascript - 在谷歌地图中获取地址和邮政编码以及经度和纬度

html - 由于导航栏, flex 的边框被隐藏

Javascript 为多个元素设置 CSS 类(一个元素集,其余元素未设置)

reactjs - 使用 react-hook-form 进行表单模式验证