我有一个简单的注册表格,如下面的代码所示,旨在在提交时显示我的验证消息。该代码主要是在react和纯js中。

import React from 'react';

class Register extends React.Component {

    constructor() {
        super();
        this.handleSubmit  = this.handleSubmit.bind(this);
        this.validationMsg = [];
    }

    handleSubmit(event) {
        event.preventDefault();

        let target   = event.target;

        for (let i = 0; i < target.length; i++) {

            let item = target.elements[i];
            let name = item.getAttribute("name")
            let msg  = name + ' is required.'

            if (item.value === '') {
                this.validationMsg.push({
                    [name]: msg
                });
            }
        }
        console.log('validationMsg', this.validationMsg);
    }

    render () {
        return (
            <form onSubmit={this.handleSubmit}>
                <input type="text" name="username" />
                {this.validationMsg.username}
                <input type="text" name="email" />
                {this.validationMsg.email}
                <input type="submit" name="submit" value="SIGN UP" />
            </form>
        );
    }
}

export default Register;


我的问题是如何从
this.validationMsg方法。

基本上说的是我的render{this.validationMsg.username}无法正常工作,这意味着它没有显示任何内容,也没有引发任何错误。

但是,当我单击提交时,我可以在{this.validationMsg.email}函数中查看我想要的结果

console.log('validationMsg', this.validationMsg);


如何在render()方法中显示this.validationMsg中的值?

最佳答案

错误消息实际上存储在类的normal variable中。因此,该组件将不会呈现以显示错误消息。您应该将其存储在组件state中。您可以找到有关React组件如何处理数据更改的更多详细信息here

这是使用状态的更新代码。和工作中的codepen

class Register extends React.Component {
    constructor() {
        super();
        this.handleSubmit  = this.handleSubmit.bind(this);
        this.state = {
          validationMsg: {}
        };
    }

    handleSubmit(event) {
        event.preventDefault();

        let target = event.target;
        const validationMsg = {};

        for (let i = 0; i < target.length; i++) {

            let item = target.elements[i];
            let name = item.getAttribute("name")
            let msg  = name + ' is required.'

            if (item.value === '') {
              validationMsg[name] = msg;
            }
        }
        this.setState({ validationMsg });
    }

    render () {
        return (
            <form onSubmit={this.handleSubmit}>
                <input type="text" name="username" />
                {this.state.validationMsg.username}
                <input type="text" name="email" />
                {this.state.validationMsg.email}
                <input type="submit" name="submit" value="SIGN UP" />
            </form>
        );
    }
}

09-10 23:40