简体   繁体   English

如何根据 React 上的输入表单禁用/启用按钮?

[英]How can I disable/enable a button depending on an Input Form on React?

I have created a Form Input, so people can send me an email.我创建了一个表单输入,因此人们可以给我发送 email。 I want my button to only be active if there are no error messages from the different inputs.我希望我的按钮只有在没有来自不同输入的错误消息时才处于活动状态。 By now, the button is disabled when the page first renders, but after I fill the first input with validation (email), it becomes enabled.到目前为止,该按钮在页面首次呈现时被禁用,但在我用验证(电子邮件)填充第一个输入后,它就变为启用状态。 I want it to just be enabled once all inputs are correctly filled.我希望它在所有输入都正确填充后才启用。 Also, if I fill all the inputs, but then clean one, I want the button to become disabled.另外,如果我填写了所有输入,然后清理了一个,我希望按钮被禁用。

Can you help me?你能帮助我吗?

See the code below:请看下面的代码:

const validateForm = (errors) => {
  let valid = true;
  Object.values(errors).forEach(
    (val) => val.length > 0 && (valid = false)
  );
  return valid;
}

class Form2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isDisabled: true,
      firstName: null,
      email: null,
      subject: null,
      message: null,
      errors: {
        firstName: "",
        email: "",
        subject: "",
        message: "",

      }
    };
  }

  handleSubmit = (e) => {
    e.preventDefault();
    emailjs.sendForm('gmail', 'template_test', e.target, "***************")
    if(validateForm(this.state.errors)) {
      console.info("Valid Form")
    }else{
      console.error("Invalid Form")
    }
    e.target.reset();
  }

  handleChange = (event) => {
    event.preventDefault();
    const { name, value } = event.target;
    let errors = this.state.errors;

    switch (name) {
      case "firstName": 
        errors.firstName = 
          value.length < 3
            ? "Enter your name"
            : "";
        break;
      case "email": 
        errors.email = 
          validEmailRegex.test(value)
            ? ""
            : "Enter a valid email address";
        break;
      case "subject": 
        errors.subject = 
          value.length < 3
            ? "Enter a subject at least 3 characters long"
            : "";
        break;
      case "message" :
        errors.message =
        value.length < 10
            ? "Enter your message. It must be at least 10 characters long"
            : "";
      default:
        break;
    }

    this.setState({errors, [name]: value});

    if(errors.email.length < 1 && errors.subject.length < 1 && errors.message.length < 1){
      this.setState({isDisabled: false})
    } else if(errors.email.length > 0 && errors.subject.length > 0 && errors.message.length > 0){
      this.setState({isDisabled: true})
    }
  }

  
  render(){
    const {errors} = this.state;
  return (
    <div>
     <div className="container fluid">
       <form onSubmit={this.handleSubmit}>
        <div className="row pt-5 mx-auto">
          <div className="col-8 form-group mx-auto">
            <input type="text" className="form-control" placeholder="Name" name="name"/>
            {errors.firstName.length > 0 && 
                <span className='error'>{errors.firstName}</span>}
          </div>
          <div className="col-8 form-group pt-2 mx-auto">
            <input type="email" className="form-control" placeholder="Email Address" name="email" onChange={this.handleChange} noValidate/>
            {errors.email.length > 0 && 
                <span className='error'>{errors.email}</span>}
          </div>
          <div className="col-8 form-group pt-2 mx-auto">
            <input type="text" className="form-control" placeholder="Subject" name="subject" onChange={this.handleChange} noValidate/>
            {errors.subject.length > 0 &&
              <span className="error">{errors.subject}</span>}
          </div>
          <div className="col-8 form-group pt-2 mx-auto">
            <textarea className="form-control" id="" cols="30" rows="8" placeholder="Your message" name="message" onChange={this.handleChange} noValidate></textarea>
              {errors.message.length > 0 &&
              <span className="error">{errors.message}</span>}
          </div>
          <div className="col-8 pt-3 mx-auto">
            <button className="btn btn-dark" disabled={this.state.isDisabled}>Submit</button>
          </div>
        </div>
       </form>
     </div>
   </div>
)
}
}

export default Form2;

On your handleChange method, if there was any error, set the state of of isDisabled to true, otherwise set it to false.在你的handleChange方法上,如果有任何错误,将isDisabled的isDisabled设置为true,否则设置为false。

You forgot your logic:) Just put ||你忘了你的逻辑:) 放|| instead of && in this block:而不是&&在这个块:

if (errors.email.length > 0 && errors.subject.length > 0 && errors.message.length > 0) {
    this.setState({isDisabled: false})
} else if (errors.email.length === 0 || errors.subject.length === 0 || errors.message.length === 0) {
    this.setState({isDisabled: true})
}

Based on the way you trigger your onChange function, I would actually assign default values to your error messages.根据您触发onChange function 的方式,我实际上会为您的错误消息分配默认值。

      errors: {
        firstName: " ",
        email: " ",
        subject: " ",
        message: " "
      }

Otherwise your switch statement will enable the form as soon as at least one field is properly filled.否则,只要正确填写了至少一个字段,您的 switch 语句就会启用该表单。

Once you do that, your if block logic becomes a heck of a lot simpler:一旦你这样做了,你的if块逻辑就变得简单多了:

    if (
      errors.email.length === 0 &&
      errors.subject.length === 0 &&
      errors.message.length === 0 &&
      errors.firstName.length === 0
    ) {
      this.setState({ isDisabled: false });
    } else {
      this.setState({ isDisabled: true });
    }

Also you don't seem to have an onChange attached to your name field, so I fixed that as well.此外,您的姓名字段似乎没有附加onChange ,所以我也修复了它。 Anyway, here is a working version: https://codesandbox.io/s/upbeat-ritchie-sz7zl?file=/src/App.js无论如何,这是一个工作版本: https://codesandbox.io/s/upbeat-ritchie-sz7zl?file=/src/App.js

Also note that instead of putting a space into all of your default error messages, because this does seem like a bit of a hack, you could simply fill them with the actual messages as in另请注意,不要在所有默认错误消息中添加空格,因为这看起来有点像 hack,您可以简单地用实际消息填充它们,如

errors: {
        firstName: "Enter your name",
        email: "Enter a valid email",
        subject: "Enter a subject at least 3 characters long",
        message: "Enter your message. It must be at least 10 characters long"
      }

But this would depend on whether you're ok with displaying those on page load.但这取决于您是否可以在页面加载时显示这些内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据 React.js 中的多个复选框状态禁用/启用按钮 - How can I disable/enable the button based on multiple checkboxes state in React.js 我如何只启用一个按钮 onclick 并使用 react js 禁用所有其他按钮 - how i can enable only one button onclick and disable all other using react js 如果表单字符串输入为空 React,如何禁用按钮 - How to Disable Button if Form String Input is Empty React 反应如何禁用提交按钮,直到输入表单值 - React how to disable submit button until form values are input 根据父输入功能和单击按钮反应禁用和启用按钮 - React disable and enable button based on parent input function and click of button 如何使用反应启用/禁用自定义验证按钮 - How to enable/disable button on custom validation with react 如何根据条件启用/禁用反应表单 - How to enable/ disable react form based on condition 在 onBlur 模式下使用 react-hook-form 启用/禁用提交按钮 - Enable/disable submit button with react-hook-form in onBlur mode React,Material UI,如何根据状态 2 切换按钮禁用按钮 - React, Material UI, how disable button depending on the state 2 switch button Javascript:如何根据输入值的长度禁用按钮 - Javascript: How to disable button depending on the length of input value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM