我试图根据传递的电子邮件的有效性来启用或禁用我的“提交”按钮。但是,我使用的RegExp表达式无法正确读取字符串。我试过仅用email.length> 0来测试我的isWorking()函数,以确保传递给isWorking()的任何东西的确是字符串,我们很好,但是RegExp总是返回false而不管它的输入是什么。收到。我在这个应用程序中使用没有JSX的React。任何帮助将不胜感激。非常感谢!

    const validEmailRegex = RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);

    class Signup extends React.Component {

    constructor() {
       super();
       this.state = {
       email: ""
    };
       this.handleSubmit = this.handleSubmit.bind(this);
    }

    isWorking () {
       const email = event.target;
       //if (email.length > 0) {
       //  return false;
       // }
       // return true;

    if (validEmailRegex.test(email) === true) {
       return false;
       }
       return true;
    }

    handleSubmit(event) {
        event.preventDefault();

    if (!event.target.checkValidity()) {
        this.setState({
        invalid: true,
        displayErrors: true,
    });
    return;
    }

    const form = event.target;
    const data = new FormData(form);

    for (let name of data.keys()) {
        const input = form.elements[name];
        const parserName = input.dataset.parse;
        console.log('parser name is', parserName);

        if (parserName) {
        const parsedValue = inputParsers[parserName](data.get(name));
        data.set(name, parsedValue);
        }
    }

    this.setState({
        res: stringifyFormData(data),
        invalid: false,
        displayErrors: false,
    });
}

  render() {

     const { res, invalid, displayErrors } = this.state;

     //pass data to the button for disabling or not
     const isEnabled = this.isWorking();

      return (

      React.createElement("div", { className: "container" },

      React.createElement("div", { className: "row" },

        React.createElement("form", { onSubmit: this.handleSubmit, noValidate: true, className: displayErrors ? 'displayErrors' : '' },
          React.createElement("input", { className: "form-control", name: "formEmail", id: "formEmail", type: "email", placeholder: "email"}),
        ),

        React.createElement("span", { className: "span"},
          React.createElement("fieldset", { className: "form-group" },
            React.createElement(Link, { className: "nav-link", activeClassName: "nav-link-active", to: "/contact" },

              React.createElement("button", { className: "button1", disabled: isEnabled, type: "button"}, "next")
            ),
          )
        ),
    ),
  )
);
}
}

最佳答案

您的isWorking()不会从任何地方接收事件。同样,event.target将是一个HTML元素,并且绝对不是输入值。对于表单,您可以执行event.target.elements["<name_of_input>"](如果为formEmail,则为输入名称)以获取输入值。

08-18 10:50