【问题标题】:how to add required attribute to checkbox in react?如何在反应中向复选框添加必需的属性?
【发布时间】:2019-07-25 09:59:58
【问题描述】:

我在input type="checkbox"中添加了属性required

   return (
     <form onSubmit={handleSubmit} action="/questions" method="post">
       <div>
         <label name="agreed">
           <input type="checkbox" required name="agreed" />
             I agree
         </label>
       </div>
     </form>
   );

但是当你点击提交表单按钮时会出现错误

An invalid form control with name='agreed' is not focusable.

我希望看到标准浏览器警告。是真的吗?

【问题讨论】:

标签: javascript reactjs forms


【解决方案1】:

这很好用

import React, { Component } from "react";

class App extends Component {
  state = {};
  handleSubmit = e => {
    console.log("Trying to submit");
    e.preventDefault();
  };
  render() {
    return (
      <form onSubmit={this.handleSubmit} action="/questions" method="post">
        <div>
          <label htmlFor="agreed">Accept </label>
          <input type="checkbox" required name="agreed" />I agree
        </div>
        <div>
          <button type="submit">Submit</button>
        </div>
      </form>
    );
  }
}

export default App;

【讨论】:

  • @evans 你所说的标准浏览器行为是什么意思??
猜你喜欢
  • 2021-10-20
  • 1970-01-01
  • 2013-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 1970-01-01
相关资源
最近更新 更多