如何知道Reactstrap表单的输入/表单字段的状态?

时间:2018-12-22 00:28:57

标签: reactjs

我想对我的reactstrap表单字段进行验证。我如何知道原始状态,脏状态等字段的状态 如何使字段的错误仅在被触摸之后才可见,而在组件首次呈现时却不可见。

除了我期望的那样,代码运行正常 这些字段显示了第一次渲染时出现的错误,经过长时间尝试后我无法完成。

import. React, { Component } from 'react';
import { Link } from 'react-router-dom';
import GoogleLogin from 'react-google-login';
import axios from 'axios';
import { connect } from 'react-redux';
import { loginUser } from '../../actions/authActions';
import PropTypes from 'prop-types';

import API_ROOT from '../../Api';
// import './Login.css';
import { FormErrors } from '../FormErrors';
import {
    Button,
    Card, CardBody,
    CardGroup, Col,
    FormFeedback,
    Container, Form,
    Input, InputGroup,
    InputGroupAddon, InputGroupText,
    Row
} from 'reactstrap';
const responseGoogle = (response) => {
    console.log(response);
}
class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: false,
            email: "",
            password: "",
            formErrors: { email: '', password: '' },
            emailValid: false,
            passwordValid: false,
            formValid: false
        };
    }

    componentDidMount() {
        console.log("login props", this.props)
        if (this.props.auth.isAuthenticated) {
            this.props.history.push('/dashboard');
        }
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.auth.isAuthenticated) {
            this.props.history.push('/dashboard');
        }
        if (nextProps.errors) {
            this.setState({ errors: nextProps.errors });
        }
    }
    onChange = (e) => {
        this.handleUserInput(e)
    }
    handleUserInput(e) {
        const name = e.target.name;
        const value = e.target.value;
        this.setState({ [name]: value },
            () => { this.validateField(name, value) });
        console.log("handle user input", this.state)
    }
    validateField(fieldName, value) {
        let fieldValidationErrors = this.state.formErrors;
        let emailValid = this.state.emailValid;
        let passwordValid = this.state.passwordValid;
        console.log("validationfiled ", this.state)

        switch (fieldName) {
            case 'email':
                emailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
                fieldValidationErrors.email = emailValid ? '' : ' is invalid';
                break;
            case 'password':
                passwordValid = value.length >= 6;
                fieldValidationErrors.password = passwordValid ? '' : ' is too short';
                break;
            default:
                break;
        }
        this.setState({
            formErrors: fieldValidationErrors,
            emailValid: emailValid,
            passwordValid: passwordValid
        }, this.validateForm);
    }

    validateForm() {
        this.setState({ formValid: this.state.emailValid && this.state.passwordValid });
    }
    errorClass(error) {
        return (error.length === 0 ? '' : 'has-error');
    }

    onSubmit = (e) => {
        e.preventDefault();
        console.log(e)
        const userData = {
            email: this.state.email,
            password: this.state.password
        };
        console.log(userData)

        this.props.loginUser(userData);
    }
Input
    render() {
        console.log(Form.Input)
        return (
            <div className="app flex-row align-items-center">
                <Container>
                    <Row className="justify-content-center">
                        <Col md="8">
                            <CardGroup>
                                <Card className="p-4">
                                    <CardBody>
                                        <Form onSubmit={this.onSubmit}  >
                                            <h1>Login</h1>
                                            <p className="text-muted">Sign In to your account</p>
                                            <InputGroup className="mb-3">
                                                <InputGroupAddon addonType="prepend">
                                                    <InputGroupText>
                                                        <i className="icon-user"></i>
                                                    </InputGroupText>
                                                </InputGroupAddon>
                                                <Input invalid={!this.state.emailValid} type="text" name="email" value={this.state.email} placeholder="Username" onChange={this.onChange} />
                                                <FormFeedback>Valid Email is required  </FormFeedback>
                                            </InputGroup>
                                            <InputGroup className="mb-4">
                                                <InputGroupAddon addonType="prepend">
                                                    <InputGroupText>
                                                        <i className="icon-lock"></i>
                                                    </InputGroupText>
                                                </InputGroupAddon>
                                                <Input invalid={!this.state.passwordValid} type="password" name="password" value={this.state.password} placeholder="Password" onChange={this.onChange}  />
                                                <FormFeedback>Password of at least 6 character is Required</FormFeedback>
                                            </InputGroup>
                                            <Row>
                                                <Col xs="6">
                                                    <Button color="primary" className="px-4">Login</Button>
                                                </Col>
                                                <Link to="/forgotpassword">
                                                    <Col xs="6" className="text-right">
                                                        <Button color="link" className="px-0">Forgot password?</Button>
                                                    </Col>
                                                </Link>
                                            </Row>
                                        </Form>
                                    </CardBody>
                                </Card>
                                <Card className="text-white bg-primary py-5 d-md-down-none" style={{ width: '44%' }}>
                                    <CardBody className="text-center">
                                        <div>
                                            <h2>Sign up</h2>
                                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                          labore et dolore magna aliqua.</p>
                                            <Link to="/signup">
                                                <Button color="primary" className="mt-3" active tabIndex={-1}>Register Now!</Button>
                                            </Link>
                                        </div>
                                    </CardBody>
                                </Card>
                            </CardGroup>
                        </Col>
                    </Row>
                </Container>
            </div>
        );
    }
}

Login.propTypes = {
    loginUser: PropTypes.func.isRequired,
    auth: PropTypes.object.isRequired,
    errors: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
    auth: state.auth,
    errors: state.errors
});

export default connect(mapStateToProps, { loginUser })(Login)

1 个答案:

答案 0 :(得分:0)

我意识到这是一个非常老的问题,但是我遇到了同样的麻烦,并认为我会发布我的解决方案,以防对他人有所帮助。

除了有效性字段的初始值(this.state.emailValid,this.state.passwordValid等)应等于true之外,所有内容都与原始问题中发布的代码完全相同。 / p>

onChange处理程序应该能够告诉我们该字段是否被触摸过,以便与这些字段的初始值一起提供我们所需要的内容。

从此:

  this.state = {
    isLoading: false,
    email: "",
    password: "",
    formErrors: { email: '', password: '' },
    emailValid: false,
    passwordValid: false,
    formValid: false
  };

对此:

  this.state = {
    isLoading: false,
    email: "",
    password: "",
    formErrors: { email: '', password: '' },
    emailValid: true,
    passwordValid: true,
    formValid: true
  };