簡體   English   中英

如何知道 reactstrap 表單的輸入/表單字段的狀態?

[英]How to know the state of input/form fields of reactstrap form?

我想對我的 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)

我意識到這是一個非常古老的問題,但我遇到了同樣的麻煩,並認為我會發布我的解決方案以防它對其他人有幫助。

一切都與原始問題中發布的代碼完全相同,除了有效性字段的初始值(this.state.emailValid、this.state.passwordValid 等)應該等於 true。

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
  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM