【问题标题】:Animation not working on component in ReactJS.动画不适用于 ReactJS 中的组件。
【发布时间】:2019-06-01 07:15:51
【问题描述】:

美好的一天。我一直在尝试在 ReactJS 中创建演示 here 的动画。我使用那个codepen作为一个松散的参考,但是当我在我自己的项目上按下登录按钮时,动画不起作用,在login page上实现了这个效果。

我做错了什么?

提前致谢, 杜克 J. 摩根。

据我所知,我的项目的特定方面是登录页面中的主要组件,在这个问题中,这可能是我上面提到的问题的原因:

import React, { Component } from 'react';

class LoginComponent extends Component {
constructor(props) {
    super(props)
    this.state = {
        incorrect: false
    }

}

onLoginButtonClick() {
    let passwordInput = document.getElementById("passwordInput");

    if (passwordInput.innerHTML !== "test") {
        // passwordInput.classList.add("incorrect-login");
        let copy = this.state;
        copy.incorrect = true;
        console.log(`Incorrect boolean: ${copy.incorrect}`);
        this.setState(copy);
        return;
    }

    this.props.setPage();
}

render() { 
    return (<div className="box" id="loginBox">
        <h2 className="title">Username</h2>
        <input type="text" placeholder="Username" className="input"/>
        <h2 className="title">Password</h2>
        <input id="passwordInput" placeholder="Password" className={`input ${this.state.incorrect ? 'incorrect-login' : ''}`} type="password"/>
        {/* <a href="#">Forgot Password?</a> */}
        <button className="button" id="login" onClick={() => {this.onLoginButtonClick()}}>Login</button>
    </div>);
}
}
export default LoginComponent;


//The CSS of the login box. incorrect-login is the class added to the password input element when the login button is clicked but the incorrect password, or no password, has been entered. 
#loginBox {
.title:nth-child(1) {
    margin-bottom: 10px;
}

.title:nth-child(3) {
    margin-bottom: 10px;
    margin-top: 10px;
}

.incorrect-login {
    margin: 4px auto;
    width: 70%;
    height: 15%;
    display: block;
    padding: 5px;
    padding-left: 10px;
    border: 2px solid red;
    animation: move 10s;
}
}

@keyframes move {
0%, 100% { left: 0px;}
20% , 60%{left: 15px;}
40% , 80%{left: -15px;}
}

【问题讨论】:

    标签: css reactjs frontend


    【解决方案1】:

    问题出在 CSS 中。我认为您应该为登录和不正确的登录创建单独的类。

    .login {
        margin: 4px auto;
        width: 70%;
        height: 15%;
        display: block;
        padding: 5px;
        padding-left: 10px;
        position: absolute;
    }
    
    .incorrect-login {
        border: 2px solid red;
        animation: move 10s;
    }
    

    如果你想在动画中使用属性“left”,你还需要添加属性 position: absolute;到组件的类。

    密码输入类名的代码应该是:

    className={`input ${this.state.incorrect ? 'login incorrect-login' : 'login'}`}
    

    你也不应该直接在 React 应用程序中使用 document.getElementById。如果你真的需要获取 React 创建的 dom 元素的引用,你应该改用ref prop

    【讨论】:

      猜你喜欢
      • 2017-07-05
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多